English 中文(简体)
• 如何捕获在植物检疫中用物体的任何方法?
原标题:How to catch any method call on object in PHP?

我正试图说明如何捕获在PHP中标的的任何方法。 我知道磁力功能(>>-quest/code>,但只有在所指物体上不存在的方法时才启动。

例如,我有这样的情况:

class Foo
{
  public function bar()
  {
    echo  foobar ;
  }

  public function override($method_name,$method_args)
  {
    echo  Calling method  ,$method_name, <br /> ;
    $this->$method_name($method_args); //dirty, but working
  }
}

当我们这样做时:

$foo = new Foo();
$foo->bar();

我希望这一产出:

Calling method bar
foobar

而不是:

foobar

是否有办法这样做? 帮助请:

最佳回答

采用原有的<代码>Foo,请填写decorator。 等等:

class Foo 
{
    public function bar() {
        echo  foobar ;
    }
}

class Decorator 
{
    protected $foo;

    public function __construct(Foo $foo) {
       $this->foo = $foo;
    }

    public function __call($method_name, $args) {
       echo  Calling method  ,$method_name, <br /> ;
       return call_user_func_array(array($this->foo, $method_name), $args);
    }
}

$foo = new Decorator(new Foo());
$foo->bar();
问题回答

您可以把物体周围打上一个物体,拦截然后向原物体发出的任何呼吁,并将结果退回。

仅将物体作为包装类别的一种变量加以储存,并在包装类别中采用超载方法,在物体上打上/设计/植被/检查。

$object = new AnyObject;
$object = new Wrapper($object);

$object->anyMethod();
$object->anyVar =  test ;
echo $object->anyVar;
echo $object[ array form ];

选择ach子的包装类别可能更加困难。 Havent试图这样做。

如果你将这一职能定在私人手中,那么电话就会把从外部向它提出的任何呼吁都锁定在“召唤”之中,但你可以从内部打电话。

class Foo
{
   private function bar()
   {
      echo  foobar ;
   }

   public function __call($method_name,$method_args)
   {
      echo  Calling method  ,$method_name, <br /> ;
      $this->$method_name(); //dirty, but working
   }
}




相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签