[英]PHP Syntax - Curly braces
So I have a simple class; 所以我有一堂简单的课;
class Foo{
public function bar(){
// Do something
}
}
$method = 'bar';
$object = new Foo;
Using 使用
$object->{ $method }()
seems to work the same as writing 似乎和写作一样
$object->$method()
Is there any difference between these and if not, why would you write it one way or the other? 这些之间有什么区别,如果没有,为什么还要用另一种方式写呢?
Difference between these styles become significant when instead of simple $method
you use, for example, this: 例如,使用以下
$method
代替简单的$method
时,这些样式之间的差异变得很明显:
class Baz {
public function getMethodName()
{
return 'bar';
}
}
class Foo{
public function bar(){
echo 'bar_run';
}
}
$method = 'bar';
$object = new Foo;
$yao = new Baz();
// see this line:
$object->{$yao->getMethodName()}(); // outputs `bar_run`
// if you omit `{}`:
$object->$yao->getMethodName()(); // fatal error
So, {}
should be used when it's not clear how to parse your code. 因此,在不清楚如何解析代码时,应使用
{}
。
Of course, such codes like $object->{$yao->getMethodName()}();
当然,这样的代码例如
$object->{$yao->getMethodName()}();
must be avoided. 必须避免。 But still if there's some case in which it's not clearly understood how to execute an expression - better use
{}
. 但是,即使在某些情况下,仍不清楚如何执行表达式,最好使用
{}
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.