微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php-通过反射传递参数

This article具有以下方法

/**
 * 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文档的Function arguments部分中:

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.

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

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

<?PHP

// 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

Run demo

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐