Nytrix Nytrix - 1 month ago 5
PHP Question

PHP - __call() confusion

I have some confusion with

__call()
and everything I search about it tells me it should work

<?php

class A {

abstract public function C();

private function B(){
echo "B";
}

public function __call($method,$arguments){
if(method_exists("C", $method)) {
$this->B();
return call_user_func_array(array("C",$method),$arguments);
}
}
}

class B extends A{

public function C(){
echo "C";
}
}

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

//the result I get:
// C
//the result I want;
// BC
?>


So, what I want as result is that I call function
C
but
B
get's echo'd out first. It worked at some point even, I am just really confused at what is going on. The php manual isn't that clear about it either, at least not what I am trying to do.


note: The most confusing is, the above __call method is not reponsive anymore, if I do a test message in there, doesn't print it.


As said, I've got it to work at some magical moment. Can someone point me to what I am doing wrong, or is it possible? ( I have changed some stuff over time, so that might have changed the scenario.

Answer

I think you're confusing what __call does. It's for inaccessible methods. So let's take A

class A {

    abstract public function C();

    private function B(){
        echo "B";
    }

    public function __call($method,$arguments){
        if(method_exists("C", $method)) {
            $this->B();
            return call_user_func_array(array("C",$method),$arguments);
        }
    }
}

Now, your B() is private but C() in your child is not

class B extends A{

    public function C(){
        echo "C";
    }
}

The problem is your code never touches B() the method. You're calling B() the class

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

To get __call to work you need to do

$b = new B();
$b->B(); // invokes __call()
Comments