Olaf Erlandsen
Olaf Erlandsen

Reputation: 6036

how to create a variable in subclass in 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;
    }
}
?>

Upvotes: 0

Views: 1395

Answers (1)

bfavaretto
bfavaretto

Reputation: 71908

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.

Upvotes: 4

Related Questions