Reputation: 1
I am trying to call several methods from a class 'Content', i.e.
$content .= Content::page_contact_us();
Except page_contact_us can be anything...
I tried
$method = 'Content::page_contact_us()';
$content .= $$method_name;
And $content
was blank...
Upvotes: 0
Views: 141
Reputation: 7617
You can achieve that using PHP's call_user_func()
. Here's how:
<?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)
Upvotes: 0
Reputation: 66217
A method name can be a variable, in the same way a function name can be a variable:
<?php
class Content
{
public static function foo()
{
echo 'Hello';
}
}
$name = 'foo';
echo Content::$name(); // Outputs 'Hello'
If you really do need/mean anything, call_user_func allows calling anything:
$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
There are further examples in the callable docs.
Upvotes: 2
Reputation: 42460
You can use the following syntax to call variable functions:
$func = 'foo';
$func(); // This calls foo()
Or, in your case:
$method = 'Content::page_contact_us';
$content .= $method();
Upvotes: 1