如何在PHP5中的子类中创建变量


how to create a variable in subclass in PHP5

我需要创建一个带有父类的变量。示例:

父类

<?php
class parentClass
{
    function __construct()
    {
        $subClass = new subClass();
        $subClass->newVariable = true;
        call_user_func_array( array( $subClass , 'now' ) , array() );
    }
}
?>

子类

<?php
class subClass extends parentClass
{
    public function now()
    {
        if( $this->newVariable )
        {
            echo "Feel Good!!!";
        }else{
            echo "Feel Bad!!";
        }
        echo false;
    }
}
?>

执行parentClass

<?php
$parentClass = new parentClass();
?>

当前

注意:subClass.php中未定义的属性:subClass::$newVariable第6行

我真的需要这个:

感觉很好!!!

解决方案:

<?php
class parentClass
{
    public $newVariable = false;
    function __construct()
    {
        $subClass = new subClass();
        $subClass->newVariable = true;
        call_user_func_array( array( $subClass , 'now' ) , array() );
    }
}
?>
<?php
class subClass extends parentClass
{
    public function now()
    {
        if( $this->newVariable )
        {
            echo "Feel Good!!!";
        }else{
            echo "Feel Bad!!";
        }
        echo false;
    }
}
?>

您必须在子类中声明属性:

<?php
class subClass extends parentClass
{
    public $newVariable;
    public function now()
    {
        if( $this->newVariable )
        {
            echo "Feel Good!!!";
        }else{
            echo "Feel Bad!!";
        }
        echo false;
    }
}
?>

编辑

要么是这样,要么使用魔术方法,这不是很优雅,而且可能会使代码难以调试。