views:

357

answers:

3

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!

+1  A: 

No, you can't pass something else to the function as that defeats the purpose of the static typing. In this situation, something like C# nullable would be nice i.e. NSNode?

I'd suggest creating NSNode::insertFirst() although I think that you have it the wrong way round, why is a node inserting itself, shouldn't the collection be inserting and taking the node as a parameter?

Geoff
+6  A: 

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
Owen
+1  A: 

Better to have a function insertAtBeginning() or insertFirst() for legibility anyway.

"The way you think of it" may not be the way the next guy thinks of it.

insertAfter(null) might mean many things.

Maybe null is a valid value and insertAfter means place it after the index that contains the value null.

Allain Lalonde