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
  • 193,403
  • 52
  • 435
  • 836
Olaf Erlandsen
  • 5,817
  • 9
  • 41
  • 73

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
  • 71,580
  • 16
  • 111
  • 150