Reputation: 1139
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.
Upvotes: 2
Views: 126
Reputation: 31624
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()
Upvotes: 3
Reputation: 412
__call() is only invoked when the function isn't specified/accessible --
See: https://www.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.methods
You cannot do what you are attempting to do.
Upvotes: 0