假设有可能,通过引用变量函数来传递参数,而不会在
PHP中生成警告?我们不能再使用’&’运算符在函数调用中,否则我会接受(尽管这样会很容易出错,编码器应该忘记它).
这是什么启发是我发掘的旧的MysqLi包装课程(这些天,我只是使用PDO).包装器和MysqLi类之间的唯一区别是包装器抛出异常而不是返回FALSE.
- class DBException extends RuntimeException {}
- ...
- class MysqLi_throwing extends MysqLi {
- ...
- function prepare($query) {
- $stmt = parent::prepare($query);
- if (!$stmt) {
- throw new DBException($this->error,$this->errno);
- }
- return new MysqLi_stmt_throwing($this,$query,$stmt);
- }
- }
- // I don't remember why I switched from extension to composition,but
- // it shouldn't matter for this question.
- class MysqLi_stmt_throwing /* extends MysqLi_stmt */ {
- protected $_link,$_query,$_delegate;
- public function __construct($link,$prepared) {
- //parent::__construct($link,$query);
- $this->_link = $link;
- $this->_query = $query;
- $this->_delegate = $prepared;
- }
- function bind_param($name,&$var) {
- return $this->_delegate->bind_param($name,$var);
- }
- function __call($name,$args) {
- //$rslt = call_user_func_array(array($this,'parent::' . $name),$args);
- $rslt = call_user_func_array(array($this->_delegate,$name),$args);
- if (False === $rslt) {
- throw new DBException($this->_link->error,$this->errno);
- }
- return $rslt;
- }
- }@H_301_4@
困难在于在包装器上调用诸如bind_result的方法.可以明确定义恒定函数(例如bind_param),允许通过引用. bind_result,但是,需要所有参数都是通过引用.如果您在MysqLi_stmt_throwing的实例上调用bind_result,那么这些参数是通过值传递的,绑定将不会占用.
try { $id = Null; $stmt = $db->prepare('SELECT id FROM tbl WHERE ...'); $stmt->execute() $stmt->bind_result($id); // $id is still null at this point ... } catch (DBException $exc) { ... }@H_301_4@由于上述课程不再使用,这个问题只是一个好奇心.封装类的替代方法是不相关的.定义一个使用Null默认值的一组参数的方法是不正确的(如果定义20个参数,但该函数是用21调用的).答案甚至不需要用MysqL_stmt_throwing的方式编写;它仅仅是提供一个具体的例子.
在PHP中没有通过引用传递可变长度参数列表的方法.这是语言的基本限制.
但是,有一个数组(& $var1,& $var2 …)语法的解决方法:
- <?PHP
- /** raise all our arguments to the power of 2 */
- function pow2() {
- $args = &func_get_arg(0);
- for ($i = 0; $i< count($args); ++$i) {
- $args[$i] *= 2;
- }
- }
- $x = 1; $y = 2; $z = 3;
- pow2(array(&$x,&$y,&$z)); // this is the important line
- echo "$x,$y,$z"; // output "2,4,6"
- ?>@H_301_4@
测试也可以被声明为function test($args),但是我想说明这与func_get_args()函数族有关.它是通过引用而不是函数签名传递变量的数组(& $x).
从关于函数参数的PHP文档的评论:http://php.net/manual/en/functions.arguments.php