0

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;
    }
}
?>
hakre
  • 184,866
  • 48
  • 414
  • 792
Jorge Olaf
  • 5,290
  • 9
  • 39
  • 71

1 Answers1

4

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.

Community
  • 1
  • 1
bfavaretto
  • 70,503
  • 15
  • 107
  • 148