[英]Using a define (or a class constant) to call a variable method?
Is it possible to : 是否有可能 :
define('DEFAULT_METHOD', 'defaultMethod');
class Foo
{
public function defaultMethod() { }
}
$foo = new Foo();
$foo->DEFAULT_METHOD();
Or do I have to : 还是我必须:
$method = DEFAULT_METHOD;
$foo->$method();
And what about a class constant instead of a define ? 那用类常量而不是定义呢?
If you use a variable or constant as the method name, you have to put it into curly brackets: 如果使用变量或常量作为方法名称,则必须将其放在大括号中:
$foo->{DEFAULT_METHOD}();
The same technique works for variables, including static class attributes: 相同的技术适用于变量,包括静态类属性:
class Foo {
public static $DEFAULT_METHOD = 'defaultMethod';
public function defaultMethod() { echo "Cool!\n"; }
}
$foo = new Foo();
$foo->{FOO::$DEFAULT_METHOD}();
In fact, practically any expression that results in a valid method name could be used: 实际上,实际上可以使用任何导致有效方法名称的表达式:
$foo->{'default'.'Method'}();
You could set it to a variable first as in your example :) 您可以先将其设置为变量,如示例所示:)
Example: http://codepad.org/69W4dYP1 示例: http : //codepad.org/69W4dYP1
<?php
define('DEFAULT_METHOD', 'defaultMethod');
class Foo {
public function defaultMethod() { echo 'yay!'; }
}
$foo = new Foo();
$method = DEFAULT_METHOD;
$foo->$method();
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.