Reputation: 1217
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;
My return from index.php
is: "Default error".
What I expected: "Error func_B".
errorA
property of ClassA
change?Upvotes: 0
Views: 41
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