我没有看到 $stuff 的意义
public $stuff = false;
一个实例变量,它设置为 false 并在构造函数中立即检查。这个变量不会改变,除非它被实例化。我认为您可能一直在寻找的是一个静态变量。
Class MyClass{
public static $stuff = false;
function __construct(){ // you don't have to specify the constructor as public
if (self::$stuff){
echo 'You got some stuff!';
} else {
echo 'You ain\'t got stuff!';
}
}
}
$myclass = new MyClass(); // You ain't got stuff!
MyClass::$stuff = true;
$myclass = new MyClass(); // You got some stuff!
如果它打算成为一个实例变量,那么您唯一需要的就是在子类化时
Class MyClass{
public $stuff = false;
function __construct(){
if ($this->stuff){
echo 'You got some stuff!';
} else {
echo 'You ain\'t got stuff!';
}
}
}
class MySubClass extends MyClass {
public $stuff = true;
}
$mysub = new MySubClass() // You got some stuff!
如果您只想将东西传递给构造函数,为什么还要定义实例变量?以下内容不应该足够吗?除非您以后必须参考它,在这种情况下,蒂姆库珀的回答。
Class MyClass {
function __construct($stuff = false){
if ($stuff){
echo 'You got some stuff!';
} else {
echo 'You ain\'t got stuff!';
}
}
}