I need something like this for my school project.
class Node {
Node $obj;
}
How do I do this in PHP?
No, it's not possible. But you can type the parameters of a method and the return type :
class Node {
private $obj = null;
public function setNode(Node $obj) {
$this->obj = $obj;
}
public function getNode():Node {
return $this->obj;
}
}
Note that if $obj
is null
you will have an error if you use getNode()
. So you could use :?Node
to allow null return.
public function getNode():?Node { // OK if $this->obj is NULL
return $this->obj;
}
EDIT
To use an instance of the current object, you could use $this
:
class Node {
public $obj = null;
public function createInstance() {
$this->obj = $this;
}
}
$node = new Node();
$node->createInstance();
var_dump($node);
var_dump($node->obj);
Will outputs :
object(Node)#1 (1) {
["obj"]=>
*RECURSION*
}
object(Node)#1 (1) {
["obj"]=>
*RECURSION*
}
As you can see $node
and $node->obj
are the same object ( object(Node)#1
).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.