我试图从“内容”类中调用几种方法,即
$content .= Content::page_contact_us();
除了page_contact_us可以是任何东西......
我试过
$method = 'Content::page_contact_us()';
$content .= $$method_name;
$content
空白......
答案 0 :(得分:2)
方法名称可以是变量,与function name can be a variable:
的方式相同<?php
class Content
{
public static function foo()
{
echo 'Hello';
}
}
$name = 'foo';
echo Content::$name(); // Outputs 'Hello'
如果您确实需要/表示任何,call_user_func允许调用任何内容:
$result = call_user_func('time'); // a function
$result = call_user_func('Content::foo'); // a static method
$result = call_user_func(['Content', 'foo']); // a static method
$result = call_user_func([$contentObject 'someMethod']); // an instance method
the callable docs还有其他例子。
答案 1 :(得分:1)
您可以使用以下语法调用变量函数:
$func = 'foo';
$func(); // This calls foo()
或者,在您的情况下:
$method = 'Content::page_contact_us';
$content .= $method();
答案 2 :(得分:0)
您可以使用PHP call_user_func()
来实现这一目标。以下是:
<?php
class Content{
public static function whatever(){
return "This is a response from whatever Method inside the Content Class...";
}
}
$method = 'whatever';
$content = "";
$content .= Content::whatever();
$content2 = call_user_func(array('Content', $method));
var_dump($content);
var_dump($content2);
//RESPECTIVELY DISPLAYS::
'This is a response from whatever Method inside the Content Class...' (length=67)
'This is a response from whatever Method inside the Content Class...' (length=67)