php参数反射,php-通过反射传递参数

/**

* Call protected/private method of a class.

*

* @param object &$object Instantiated object that we will run method on.

* @param string $methodName Method name to call

* @param array $parameters Array of parameters to pass into method.

*

* @return mixed Method return.

*/

public function invokeMethod(&$object, $methodName, array $parameters = array())

{

$reflection = new \ReflectionClass(get_class($object));

$method = $reflection->getMethod($methodName);

$method->setAccessible(true);

return $method->invokeArgs($object, $parameters);

}

我的问题是…在函数声明中$object之前是否有&符号是否有特定原因?通常,这意味着您是通过引用传递的,但是默认情况下PHP是否不通过引用传递对象?

解决方法:

PHP supports passing arguments by value (the default), passing by reference, and default argument values. Variable-length argument lists are also supported.

默认情况下,参数按值传递.

至于对象,似乎它们是通过引用传递的,但这并非完全正确.请参阅Objects and references,其中指出:

A PHP reference is an alias, which allows two different variables to write to the same value. As of PHP 5, an object variable doesn’t contain the object itself as value anymore. It only contains an object identifier which allows object accessors to find the actual object. When an object is sent by argument, returned or assigned to another variable, the different variables are not aliases: they hold a copy of the identifier, which points to the same object.

因此,为避免混淆,我总是假设即使对于对象,也不按值传递参数.如果希望通过引用传递它,请添加&以确保您确实通过了引用.

这是一个带有对象的示例:

// Passed by value... won't be affected

function byValue($arg) {

$arg = null;

}

// Passed by reference... will be affected

function byReference(&$arg) {

$arg = null;

}

$obj = new StdClass;

var_dump($obj); // Untouched object created

byValue($obj);

var_dump($obj); // After 'trying' to set it to null

byReference($obj);

var_dump($obj); // After setting it to null for real

标签:reflection,pass-by-reference,php

来源: https://codeday.me/bug/20191111/2022863.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值