【问题标题】:how to create a variable in subclass in PHP5如何在 PHP5 的子类中创建变量
【发布时间】:2012-04-20 12:56:18
【问题描述】:

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

父类

<?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;
    }
}
?>

执行父类

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

目前

注意:未定义的属性:subClass::$newVariable in subclass.php on 第 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;
    }
}
?>

【问题讨论】:

  • var $newVariable 在子类中?
  • @eicto,我需要创建一个新变量。查看代码...谢谢!
  • 我现在看到了代码,它看起来是无限循环,不是吗?
  • @eicto,有一个循环,只有一个插件系统...
  • 为什么call_user_func_array 而不是仅仅在父类上调用$subClass-&gt;now();

标签: php oop class


【解决方案1】:

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

<?php
class subClass extends parentClass
{
    public $newVariable;

    public function now()
    {
        if( $this->newVariable )
        {
            echo "Feel Good!!!";
        }else{
            echo "Feel Bad!!";
        }
        echo false;
    }
}
?>

编辑

要么这样,要么使用magic methods,这不是很优雅,而且会让你的代码难以调试。

【讨论】:

    猜你喜欢
    • 2017-04-04
    • 1970-01-01
    • 2020-01-04
    • 1970-01-01
    • 2022-07-31
    • 1970-01-01
    • 2012-01-08
    • 2016-03-19
    • 1970-01-01
    相关资源
    最近更新 更多