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;
    }
}
?>
6
  • 2
    var $newVariable in subclass ? Commented Apr 7, 2012 at 3:11
  • @eicto, i need CREATE A NEW VARIABLE. See the code... Thanks! Commented Apr 7, 2012 at 3:13
  • 1
    i see the code now, it looks infinite loop, isn't it ? Commented Apr 7, 2012 at 3:14
  • @eicto, there is a loop, only a system of plugins... Commented Apr 7, 2012 at 3:20
  • 1
    Why call_user_func_array instead of just calling $subClass->now(); on the parent class? Commented Apr 7, 2012 at 3:22

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.