Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP5: Specifying a datatype in method parameters

Tags:

php

parameters

I have a function that looks like this

class NSNode {
    function insertAfter(NSNode $node) {
        ...
    }
}

I'd like to be able to use that function to indicate that the node is being inserted at the start, therefore it is after nothing. The way I think about that is that null means "nothing", so I'd write my function call like this:

$myNode->insertAfter(null);

Except PHP throws an error saying that it was expecting an NSNode object. I'd like to stick to using the strict data typing in my function, but would like to be able to specify a null-esque value.

So, short of changing it to function insertAfter($node) { }, is there a way I can pass something else to that function?


Update: I've accepted Owen's answer because it answered the question itself. Everyone else's suggestions were really good and I'll actually be implementing them in this project, thanks!

like image 408
nickf Avatar asked Dec 30 '22 09:12

nickf


1 Answers

sure, just set a default "null"

function(NSNode $node = null) {
// stuff....
}

result being:

$obj->insertAfter(); // no error
$obj->insertAfter(new NSNode); // no error
$obj->insertAfter($somevar); // error expected NSNode
like image 97
Owen Avatar answered Jan 08 '23 13:01

Owen