Jump to content

[SOLVED] Error with type hinting of the function parameter Page


LAPS
 Share

Recommended Posts

Hi, I've the function:

function functionName(Page $item) {
  // function code
}

If in templates I use the code

functionName($pages->get($id));

then in the logs I get the error "Argument 1 passed to functionName() must be an instance of Page, instance of ProcessWire\Page given, called in ...". However I don't get the error by removing the Page type from the function statement.

Why does it happen?

 

Link to comment
Share on other sites

Hi LAPS, based on the error message it appears the file your function lives in is not namespaced. So your type-hint Page $item is telling PHP that you expect an object of the class Page in the global namespace. All ProcessWire classes are in the Processwire namespace (check out the namespace declaration at the top of any given core PHP file). So you need to type-hint against the class in that namespace:

function functionName(\Processwire\Page $item) {
	//...
}

Alternatively, you can alias the Page class for the file with your function, or put that file in the Processwire namespace itself. At the top of the PHP file, add one of those:

// importing the Page class, this tells PHP that `Page` should be interpretated as `\Processwire\Page`
<?php
use \Processwire\Page;
// namespacing the file itself, so ´Page´ will resolve to ´\Processwire\Page´
<?php
namespace Processwire;

Hope this works for you. Cheers!

  • Like 6
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...