开发者

PHP: weird behaviour when calling a protected method via a static proxy

I find this really strange..could someone开发者_如何学编程 give an explanation?

abstract class UIController{
   public static function exec($context,$vdo){
      return call_user_func(array($context, $vdo));   
   }
}

class UIControllerSettings extends UIController{
    protected function save(){
        return "saved\n";
    }
}

$controller = new UIControllerSettings();
echo UIController::exec($controller, 'save'); //<-- prints "saved"
echo $controller->save(); // <-- throws a fatal error 

Not sure it this makes sense; shouldn't both calls produce a fatal error??

Thanks in advance.

Update:

Here is the output:

$ php --version
PHP 5.3.3-1ubuntu9.5 with Suhosin-Patch (cli) (built: May  3 2011 00:48:48) 
Copyright (c) 1997-2009 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies
$ php test.php 
saved
PHP Fatal error:  Call to protected method UIControllerSettings::save() from context '' in test.php on line 17


Class members declared public can be accessed everywhere. Members declared protected can be accessed only within the class itself and by inherited and parent classes:

http://php.net/manual/en/language.oop5.visibility.php.

Since UIController::exec() is the right way to address the public static function, my guess is the call_use_func() is being processed as a call from within the class itself. On the other hand $controler->save() can't be run because it's a protected function.


Protected methods can be called anywhere in the inheritance line of the object(parents and children). Because UIController::exec which is in UIController that is a parent of UIControllerSettings is actually calling UIControllerSettings::save and not the main code it is perfectly ok.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜