PHP5: specifying data type in method parameters

I have a function that looks like

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

I would like to be able to use this function to indicate that the node is inserted at the beginning, so it does not work. I think of this that null means β€œnothing,” so I would write my function call as follows:

 $myNode->insertAfter(null); 

In addition, PHP generates an error saying that it expects an NSNode object. I would like to adhere to strict data entry in my function, but would like to be able to specify a null-esque value.

So, without changing it to function insertAfter($node) { } , is there a way to pass something else to this function?


Update: I accepted Owen's answer because he answered the question itself. All the other proposals were really good, and I will really implement them in this project, thanks!

+4
source share
3 answers

of course just set the default value to "null"

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

result:

 $obj->insertAfter(); // no error $obj->insertAfter(new NSNode); // no error $obj->insertAfter($somevar); // error expected NSNode 
+8
source

No, you cannot pass anything else to the function, as that defeats the purpose of static input. In this situation, something like C # nullable would be nice, that is, NSNode?

I would suggest creating NSNode :: insertFirst (), although I think you have the wrong way, why insert the node itself, you should not insert the assembly and take node as a parameter?

+1
source

It is better to have the function insertAtBeginning () or insertFirst () for readability anyway.

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

insertAfter (null) can mean a lot of things.

Maybe null is a valid value, and insertAfter means putting it after an index that contains a null value.

+1
source

Source: https://habr.com/ru/post/1277552/


All Articles