我正在努力学习构造和破坏。 所以,我做了这个
<?php
class Numbers {
public function __construct($numberint,$numbername,$numberletter,$numberpos) {
$this->numberint = $numberint;
$this->numbername = $numbername;
$this->numberletter = $numberletter;
$this->numberpos = $numberpos;
}
public function __destruct() {
unset($this->numberpos);
}
}
$number1 = new Numbers(1,"One","A",0);
print_r($number1);
?>
如您所见,我创建了Number类,然后使用construct作为Objects。但是在构造之后,我想使用destruct,在这种情况下,取消设置numberpos。我试图将它们放在一起,以了解工作方式。 有人可以帮帮我吗?
我的想法是改变结果:
Numbers Object ( [numberint] => 1 [numbername] => One [numberletter] => A [numberpos] => 0 )
要...
Numbers Object ( [numberint] => 1 [numbername] => One [numberletter] => A )
感谢并记住我正在学习:D
答案 0 :(得分:1)
析构函数用于销毁整个对象,而不是对象的一部分。如果你想要你想要的输出,你可以这样做:
$number1 = new Numbers(1,"One","A",0);
print_r($number1);
unset($number1->numberpos);
print_r($number1);
如果你想看到你的析构函数被调用,请取消设置对象:
class Numbers {
public function __destruct() {
echo "Destructing!\n";
}
}
$number1 = new Numbers();
unset($number1);
echo "Done!";
输出:
Destructing!
Done!