rbz
rbz

Reputation: 1217

How to set a property of an extended class of a class stuck by itself?

Exemple

Path root

File: classA.php

class ClassA 
{
    public $returnA = null;
    public $errorA  = "Default error";

    function __construct
    {
       $this -> func_A();
    }

    public function func_A()
    {
        require_once 'classB.php';
        $obj = new ClassB;
        $obj -> func_B();
    }

}

File: classB.php

class ClassB extends ClassA
{
    public function func_B()
    {
       # attempt
       $this -> errorA = "Error func_B";
    }

}

File: index.php

require_once 'ClassA.php';

$obj = new ClassA;
echo ($obj -> returnA != null) ? $obj -> returnA : $obj -> errorA;

Problem

My return from index.php is: "Default error".

What I expected: "Error func_B".


Question

Upvotes: 0

Views: 41

Answers (1)

Syntactic Fructose
Syntactic Fructose

Reputation: 20124

You're only getting the default string because func_A() is creating a new instance of ClassB, calling a function on it then tossing it you (because you aren't returning it).

public function func_A()
{
    require_once 'classB.php';
    $obj = new ClassB; // New object instantiated
    $obj -> func_B(); // Function called on $obj

    // $obj dies here, as it is not returned and will go out of scope.
}

Essentially, func_A() performs nothing of value in your code above because it creates then throws away an object.

As for a proper solution, I would first ask why you want to encapsulate an extended class in the base class, as you are likely going about something wrong if this code is more than just a theoretical example.

Upvotes: 1

Related Questions