0

I wanna define a function in PHP with a header like this:

public function functionname(Classname $node)
{ ... }

but $node can also be NULL

when I pass NULL i get:

Catchable fatal error: Argument 1 passed to functionname() must be an instance of Classname, null given, called in phpfile.php on line xx and defined in ...

Is it possible somehow that php also lets me pass a NULL or a NULLpointer? or do i have to redefine the function like:

public function functionname($node)

and check inside with an:

if ($node != NULL)
if (typeof($node)!="Classname")
   { throw error }
Noooooob
  • 91
  • 5

1 Answers1

-1

You can define nullable type declaration:

public function functionname(Classname $node = null){}
tmt
  • 7,611
  • 4
  • 32
  • 46
  • I did exactly this seems the right way but its confusing cause I have not just 1 function I have a multiple cascading functions and i have to nullabel type declare all. Before asking this question I declared the constructor of my class like this and worked but i wondered why I have to do it also in the functions... – Noooooob Nov 27 '15 at 11:22
  • Yes, you have to specify it on every type-hinted argument of every method. I don't think there is any global way to override this. – tmt Nov 27 '15 at 11:29