php - PHP反射使用传递给构造函数的参数数组创建类实例(对象)
问题描述
如何使用 PHP 反射实例化类 Bar?
班级代码:
class Bar
{
private $one;
private $two;
public function __construct($one, $two)
{
$this->one = $one;
$this->two = $two;
}
public function get()
{
return ($this->one + $this->two);
}
}
我的想法用完了,我的一些猜测是:
$class = 'Bar';
$constructorArgumentArr = [2,3];
$reflectionMethod = new \ReflectionMethod($class,'__construct');
$object = $reflectionMethod->invokeArgs($class, $constructorArgumentArr);
echo $object->get(); //should echo 5
但这不起作用,因为 invokeArgs() 需要一个对象而不是类名,所以我有一个鸡蛋情况:我没有对象,所以我不能使用构造函数方法,我需要使用构造函数方法来获取对象。
我尝试$class
在没有对象时调用构造函数的逻辑之后将 null 作为第一个参数传递,但我得到:“ReflectionException:尝试调用非静态方法......”
如果反射没有可用的解决方案,我将接受任何其他(即 php 函数)。
解决方案
您可以使用ReflectionClass和ReflectionClass::newInstanceArgs
class Bar
{
private $one;
private $two;
public function __construct($one, $two)
{
$this->one = $one;
$this->two = $two;
}
public function get()
{
return ($this->one + $this->two);
}
}
$args = [2, 3];
$reflect = new \ReflectionClass("Bar");
$instance = $reflect->newInstanceArgs($args);
echo $instance->get();
推荐阅读
- javascript - 如何使用节点中的套接字响应代理服务器中的“CONNECT”方法请求?
- angular - 无法以角度设置和获取 cookie
- django - 使用 Django 配置 Google Cloud App Engine
- java - 在 jpql 中使用 spel 表达式在特定情况下需要 20 秒
- scala - 在运行时将 Scala 3 代码从字符串解析为 Scala 3 AST
- javascript - 仅当输入有效时,如何使用 javascript 验证在表单中显示 CSS 动画
- r - Tidymodels 错误:无法在此上下文中重命名变量
- powershell - Regedit GUI 通过命令行连接网络注册表
- reactjs - 解码 Firebase ID 令牌失败
- vue.js - 奇怪的 Vuejs 道具行为与数组