如何通过PHP中的引用传递可变参数的参数?

前端之家收集整理的这篇文章主要介绍了如何通过PHP中的引用传递可变参数的参数?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
假设有可能,通过引用变量函数来传递参数,而不会在 PHP生成警告?我们不能再使用’&’运算符在函数调用中,否则我会接受(尽管这样会很容易出错,编码器应该忘记它).

这是什么启发是我发掘的旧的MysqLi包装课程(这些天,我只是使用PDO).包装器和MysqLi类之间的唯一区别是包装器抛出异常而不是返回FALSE.

  1. class DBException extends RuntimeException {}
  2. ...
  3. class MysqLi_throwing extends MysqLi {
  4. ...
  5. function prepare($query) {
  6. $stmt = parent::prepare($query);
  7. if (!$stmt) {
  8. throw new DBException($this->error,$this->errno);
  9. }
  10. return new MysqLi_stmt_throwing($this,$query,$stmt);
  11. }
  12. }
  13. // I don't remember why I switched from extension to composition,but
  14. // it shouldn't matter for this question.
  15. class MysqLi_stmt_throwing /* extends MysqLi_stmt */ {
  16. protected $_link,$_query,$_delegate;
  17.  
  18. public function __construct($link,$prepared) {
  19. //parent::__construct($link,$query);
  20. $this->_link = $link;
  21. $this->_query = $query;
  22. $this->_delegate = $prepared;
  23. }
  24. function bind_param($name,&$var) {
  25. return $this->_delegate->bind_param($name,$var);
  26. }
  27. function __call($name,$args) {
  28. //$rslt = call_user_func_array(array($this,'parent::' . $name),$args);
  29. $rslt = call_user_func_array(array($this->_delegate,$name),$args);
  30. if (False === $rslt) {
  31. throw new DBException($this->_link->error,$this->errno);
  32. }
  33. return $rslt;
  34. }
  35. }@H_301_4@
  36. 困难在于在包装器上调用诸如bind_result方法.可以明确定义恒定函数(例如bind_param),允许通过引用. bind_result,但是,需要所有参数都是通过引用.如果您在MysqLi_stmt_throwing的实例上调用bind_result,那么这些参数是通过值传递的,绑定将不会占用.

  37. try {
  38.     $id = Null;
  39.     $stmt = $db->prepare('SELECT id FROM tbl WHERE ...');
  40.     $stmt->execute()
  41.     $stmt->bind_result($id);
  42.     // $id is still null at this point
  43.     ...
  44. } catch (DBException $exc) {
  45.    ...
  46. }@H_301_4@ 
  47.  

    由于上述课程不再使用,这个问题只是一个好奇心.封装类的替代方法是不相关的.定义一个使用Null默认值的一组参数的方法是不正确的(如果定义20个参数,但该函数是用21调用的).答案甚至不需要用MysqL_stmt_throwing的方式编写;它仅仅是提供一个具体的例子.

PHP中没有通过引用传递可变长度参数列表的方法.这是语言的基本限制.

但是,有一个数组(& $var1,& $var2 …)语法的解决方法

  1. <?PHP
  2.  
  3. /** raise all our arguments to the power of 2 */
  4. function pow2() {
  5. $args = &func_get_arg(0);
  6.  
  7. for ($i = 0; $i< count($args); ++$i) {
  8. $args[$i] *= 2;
  9. }
  10. }
  11.  
  12.  
  13. $x = 1; $y = 2; $z = 3;
  14. pow2(array(&$x,&$y,&$z)); // this is the important line
  15.  
  16. echo "$x,$y,$z"; // output "2,4,6"
  17.  
  18. ?>@H_301_4@
  19. 测试也可以被声明为function test($args),但是我想说明这与func_get_args()函数族有关.它是通过引用而不是函数签名传递变量的数组(& $x).

  20. 从关于函数参数的PHP文档的评论http://php.net/manual/en/functions.arguments.php

猜你在找的PHP相关文章