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

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...