Using $this from within a function
I have a document that is able to use 开发者_运维知识库$this
to access certain bits of info. Inside that document there is a function which cannot access $this
(gives an error about not being inside an object).
Is there any way to allow it access to $this
, so I can run the class's methods from within the function?
I have tried using globals but to no avail.
If the function is defined outside the class, you can pass in an instance of the object and use that.
For example:
class A
{
public function B()
{
echo "C";
}
}
function D($obj)
{
echo $obj->B();
}
Rewrite the function so that it expects an additional parameter. Pass $this
as argument to that function
Assuming that the function is part of the class that you are trying to get a property of use self
where you would have used this.
精彩评论