php - (new class())->someMethod() 和 (new Class)->someMethod() 之间的区别
问题描述
我正在尝试找到
(new class())->someMethod()
和之间的区别(new Class)->someMethod()
。我在本地尝试了一些代码,看起来两者都是一样的,请在这里帮助我
解决方案
class Foo {
function __construct() {
echo __METHOD__ . "\n";
}
function bar() {
echo __METHOD__ . "\n";
}
}
(new Foo())->bar();
(new Foo)->bar();
/**output
Foo::__construct
Foo::bar
Foo::__construct
Foo::bar
*/
其实没有什么不同,只是有一点点不同,
__construct 都被调用
(new class())->someMethod() //does call __construct with parameter when get instance
(new class)->someMethod() // no need call __construct when get instance
你必须(new class())->foo()
按照psr标准的方式使用它
例如
class User
{
private string $name;
public function __construct(string $name)
{
$this->name=$name;
}
}
//in tsis scenarion you have use (new User('john'));
如果不需要 _construct 参数,可以将其用作(new User)->foo().
class User
{
}
//class doesnt want _construct parameters
它必须被称为(new User())
。例如,此__construct
方法需要一个参数,尽管该参数没有出现。
class User{
public function __construct()
{
print_r(func_get_args());
}
}
(new User(1,'ff'));
推荐阅读
- amazon-web-services - 在我的 IaC 堆栈中获取自动存储桶策略的处理程序错误
- php - 如何在 WordPress 循环中显示当前帖子的评分?
- timer - Alexa 未读取 Launch_Task 的“textToConfirm”
- ios - Swift - 未正确解析负字符串到整数的转换
- python - 我可以使用 TP vs. FP 而不是 TPR vs. FPR 来制作 ROC 曲线吗?
- bigdata - write.xlsx 用于基因组数据
- sql - SQL Count of the same country,相同的名字,相同的姓氏的人相同的年龄(例如史密斯)
- javascript - 电子 ondrop 和 ondrag- 事件未触发
- c - cs50 pset4 - 边缘检测过滤器不起作用 - sobel 算子
- python - Kivy using Canvas: Key error with line while starting beyond boundaries