编程语言
首页 > 编程语言> > php-通过反射传递参数

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

标签:reflection,pass-by-reference,php
来源: https://codeday.me/bug/20191111/2022863.html