Pleace consider the following example:
class A {
public method() {
$foo = 'bar';
}
}
class B extends A {
public method {
parent::method();
echo $foo; // $foo == null
}
}
I run to situations like this quite frequently when I need to extend the functionality of a class coded by somebody else. Is there a way to have the $foo
of the aforementioned example to be not null
but bar
?
I know perfectly well, that what I'm suggesting is not a problem at all if the variable $foo
were a property of the class. However, this example applies to a situation where the class I want to extend is poorly designed and modifying the original class and changing the rogue variables into class properties is out of the question for reasons such as the class being a part of a CMS and update compatibility etc.
Unfortunately not. Once method() is called, the $foo variable is contained only within method(). You would have to change method() to either return $foo, or echo it itself. Once method() completes its run (which is quick, as all it does is create a variable), that local variable is then destroyed.
Assuming that B
is supposed to extend A
(it's not in your example although it does not matter much in this case...) there is nothing you can do without modifying class A
: The $foo
variable is only defined in the local scope of the method in class A
.
You can:
But that is about it, without modifying class A
you cannot retain or access $foo
inside that method.
No. $foo
in this case is a local variable, existing only while the method()
call is actually running. When the method returns, the local variables are cleaned up/destroyed. And even if you did something like make it a static variable, it still would exist only in the scope of method()
and not be accessible from the outside world.
You'd need to do something like:
class A {
public $foo;
function method() {
$this->foo = 'bar';
}
}
But even then, class A
would not be aware of class B
and couldn't inject foo's value into your B method's scope.