简体   繁体   中英

Automatically invoke __call of parent class when invoking public child method?

I have the following code:

class A
{
    public function __call($method, $args)
    {
        echo 'Hello';
    }
}

class B extends A
{
    public function test()
    {
        echo 'Hello world';
    }
}

$b = new B();
b->test(); //outputs 'Hello world';

Now, when invoke test() the output is: Hello world. But i want it to first echo: Hello world and than i want to echo: Hello of the parent without declaring the test method in class A.

How can i resolve this?

Edited:

Sorry maybe i wasn't clear enough and sorry for my bad english i'm from Holland, what i want is when a child's method gets invoked that the parent class gets the name of the child's method that is invoked.

__call is an overload function. Meaning that is going to get called when there is no public function defined!!!

So to get hello only call any other function that is not defined

$b = new B();
b->notAFunction();

Will give you hello only.

You can just call parent::test() this way :

class B extends A {

    public function test()
    {
        echo 'Hello world';
        parent::test();
    }
}

Outputs :

Hello WorldHello

You could rename __call to test and call parent::test() in the beginning of the child test.

There is no way to automate this.

Also like to point out that if you name __call with the two underscores, the access modifier should be private, and _call for protected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM