douzi4766 2012-04-07 03:08
浏览 36
已采纳

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

i need create a variable with parent subclass. Example:

Parent Class

<?php
class parentClass
{
    function __construct()
    {

        $subClass = new subClass();
        $subClass->newVariable = true;

        call_user_func_array( array( $subClass , 'now' ) , array() );

    }
}
?>

SubClass

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

Execute parentClass

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

Currently

Notice: Undefined property: subClass::$newVariable in subclass.php on line 6

I really need this:

Feel Good!!!

Solution:

<?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;
    }
}
?>
  • 写回答

1条回答 默认 最新

  • donljt2606 2012-04-07 03:14
    关注

    You have to declare the property in the subclass:

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

    EDIT

    It's either that, or using magic methods, which is not very elegant, and can make your code hard to debug.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏