php - PHP:通过对象属性值实例化类
问题描述
有没有办法使用对象属性的值来实例化一个新的类实例?
$arg = 'hello';
$class = $foo->bar;
$instance = new $class($arg);
这很好用,但我想跳过第二行,做一些类似的事情:
$instance = new {$foo->bar}($arg);
解决方案
在 PHP 5.0.4+ 中这很好用:
$instance = new $foo->bar($arg);
完整示例:
<?php
$foo = new foo();
$arg = 'hello';
$class = $foo->bar;
$instance = new $class($arg);
$instance = new $foo->bar($arg); // your requested shorthand
class foo {
public $bar = 'bar';
}
class bar {
public function __construct($arg) {
echo $arg;
}
}
请参阅此工作示例。
推荐阅读
- python - 如何在两个相同的类之间只获取第一类的数据
- javascript - 无法按预期运行 Javascript
- javascript - Office js/Scriptlab - excel beta api 数据验证列表失败,出现“api not found”错误,但 excel 版本正确
- java - 包文件不存在
- sql - SQL postgresql:最大值和值的总和
- amazon-web-services - 无法从路由表 aws vpc 中删除 10.0.0.0/8
- java - Hibernate:在一对一关系中获取对象时返回null
- html - 获取 :after 仅在文本而不是整个容器下添加下划线
- r - 发出列表中的匹配字符串
- javascript - 在回调之前反应 setState() 不渲染