2012-04-06 146 views
5

是否有一种神奇的方法,当从对象调用某个方法时,首先调用魔术方法。有点像__call方法,但只有在找不到方法时才会触发。当调用现有方法时执行(魔术)方法

所以在我的情况,我想是这样的:

class MyClass 
{ 
    public function __startMethod ($method, $args) 
    { 
     // a method just got called, so this is called first 
     echo ' [start] '; 
    } 

    public function helloWorld () 
    { 
     echo ' [Hello] '; 
    } 
} 

$obj = new MyClass(); 
$obj->helloWorld(); 

//Output: 
[start] [Hello] 

难道这样的事情在PHP中存在?

+1

只有'__construct'会在代码的这部分执行时调用:'$ obj = new MyClass();' – noob 2012-04-06 18:22:09

+0

@micha,请参阅我的评论在Stony ---(评论被删除) 。我不在寻找__construct()方法。这仅在创建对象时调用。我需要一个魔术方法,每次调用一个函数时都会调用它。 – w00 2012-04-06 18:26:19

+1

不,没有。用另一个方案声明你的现有方法,或使用包装器对象。 – mario 2012-04-06 18:28:37

回答

3

有没有一种直接的方式来做到这一点,但它看起来像我想像你试图实现面向方面编程的形式。 PHP中实现这一目标的几种方式,一个是设置你的类像下面这样:

class MyClass 
{ 
    public function __startMethod ($method, $args) 
    { 
     // a method just got called, so this is called first 
     echo ' [start] '; 
    } 

    public function _helloWorld () 
    { 
     echo ' [Hello] '; 
    } 

    public function __call($method, $args) 
    { 
     _startMethod($method, $args); 
     $actualMethod = '_'.$method; 
     call_user_func_array(array($this, $actualMethod), $args); 
    } 
} 

$obj = new MyClass(); 
$obj->helloWorld(); 

查找在PHP实现AOP,看看有什么最适合你的其他方式(我会看看我能找到一个链接的地方)。

编辑:这里有一个文件你http://www.liacs.nl/assets/Bachelorscripties/07-MFAPouw.pdf

+0

然后,您可以将__startMethod和_helloWorld设置为私有或受保护的,因此没有人会“剽窃”它。 – Soaku 2017-07-24 19:38:29

2

不,没有什么神奇的方法。

你可以做的最好的是为您创造功能的其它名称(如:hidden_helloWorld),再搭上所有__call的电话,并尝试调用hidden_方法(如果可用)。当然,这是唯一可能的,如果你有完全控制类和它的父母等的命名...

1

,你可以通过使你的方法私人和调用使用__call()魔术方法的方法实现它。像:

<?php 

class MyClass{ 
    function __call($methd, $args){ 
     if(method_exists($this, $mthd)){ 
      $this->$mthd($args); 
     } 
    } 

    private function mthdRequired($args){ 
     //do something or return something 
    } 

除了使用调用,mthdRequired方法不会被调用。我希望这是有用的。

+0

非常酷的主意! – 2016-11-28 11:17:22

相关问题