开发者

__call method needs to know when to pass var by reference or by value

I have an object that uses the magic __call method to call methods on different objects.

There are times when this method will be used to call a method that requires one or more of its parameters to be a reference.

As of php 5.3 call-time pass-by-reference has been deprecated so I cant rely on passing the arguments by reference. I need to predict if the arguments need to be passed by reference or value!

I will try to explain this in code. I have the following two classes:

  • Main_Object
  • Extension_Object

note: there is no inheritance structure between the two classes.

class Main_Object  {

 public function __call($method, $arguments)
 {
  // check this method is in an extended class
  // …

  $ext = new Extension_Object();

  // call method in extension object
  return call_user_func_array(array($ext, $method), $arguments);
 }
}

class Extension_Object {

 // takes two arguments
 public function foo($p1, $p2)
 {
  // ...
 }

 // takes two arguments, the first being a reference
 public function bar(&$p1, $p2)
 {
  // ...
 }
}

Currently I cant find a way to call bar() without generating a PHP error or warning

$obj =开发者_如何学C new Main_Object();

// works as expected
$obj->foo($bacon, $cheese);

// MESSAGE call-time pass-by-reference has been deprecated
$obj->bar(&$bacon, $cheese);

// WARNING parameter 1 expected to be a reference
$obj->bar($bacon, $cheese);


You could set allow_call_time_pass_reference = 1; but it's far from a good solution. There doesn't seem to be another way. Reflection might yield an answer, but I personally don't know enough about this particular issue to really advise on that...

Is it possible to pass parameters by reference using call_user_func_array()?

PHP: call_user_func_array: pass by reference issue


You could manually convert the arguments like so.

public function __call($method, $arguments) {
  $referenceable_arguments = array();
  // Gets around a limitation in PHP.
  foreach ($arguments as &$argument) {
    $referenceable_arguments[] = &$argument;
  }
  return call_user_func_array(array($this->delegate, $method), $referenceable_arguments);
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜