php call class function by string name
The callback
syntax is a little odd in PHP. What you need to do is make an array. The 1st element is the object, and the 2nd is the method.
call_user_func(array($player, 'SayHi'));
You can also do it without call_user_func
:
$player->{'SayHi'}();
Or:
$method = 'SayHi';
$player->$method();
Calling class method from string stored as class member
You need to use call_user_func
to do this:
call_user_func(array($this, $this->_auto));
Unfortunately PHP does not allow you to directly use property values as callables.
There is also a trick you could use to auto-invoke callables like this. I 'm not sure I would endorse it, but here it is. Add this implementation of __call
to your class:
public function __call($name, $args)
{
if (isset($this->$name) && is_callable($this->$name)) {
return call_user_func_array($this->$name, $args);
}
else {
throw new \Exception("No such callable $name!");
}
}
This will allow you to invoke callables, so you can call free functions:
$this->_auto = 'phpinfo';
$this->_auto();
And class methods:
$this->_auto = array($this, 'index');
$this->_auto();
And of course you can customize this behavior by tweaking what __call
invokes.
How to call a function from a string stored in a variable?
$functionName()
or call_user_func($functionName)
Call method by string?
Try:
$this->{$this->data['action']}();
Be sure to check if the action is allowed and it is callable
<?php
$action = 'myAction';
// Always use an allow-list approach to check for validity
$allowedActions = [
'myAction',
'otherAction',
];
if (!in_array($action, $allowedActions, true)) {
throw new Exception('Action is not allowed');
}
if (!is_callable([$this, $action])) {
// Throw an exception or call some other action, e.g. $this->default()
throw new Exception('Action is not callable');
}
// At this point we know it's an allowed action, and it is callable
$this->$action();
Call php class method from string with parameter
When you want to call a method on an object with call_user_func() you have to pass it an array with the first element as the object or class name that the method will be called on and the second element being the name of the method, e.g.:
$tags_array = call_user_func( array($this,'get_images_for_tag'), $row["id"]);
PHP calling a class method with class name as variable string
You're overcomplicating it a bit with the extra ${} bracketing on the class reference.
$myclass='myCLaSs';
$myObject = new $myclass();
$retval = $myObject->myFunction($stringvar, 1);
Or if you need to use call_user_func_array:
$args=array($stringvar,1);
$retval=call_user_func_array(array($myObject, 'myFunction'), $args);
When you use the ${} bracketing, you are referencing variables by a variable name. For example:
$myVariable = "A";
$aVariableThatIsHoldingAVariableName = "myVariable";
echo ${$aVariableThatIsHoldingAVariableName}; // outputs "A".
Applying this to your code shows the following logic happening:
Set the variable $myclass
equal to the string 'myclass'
$myclass='myclass';
Set the variable ${$myclass}
:
This gets the value of the variable $myclass
('myclass') and uses that as the variable name. In other words, the following variable name resolution happens: ${$myclass}
=> ${'myclass'}
=> $myclass
.
So this line sets $myclass
to a new Myclass();
object:
${$myclass}=new ucfirst($myclass);
The first parameter to call_user_func_array
is a callable
(See http://us2.php.net/manual/en/language.types.callable.php). The callback it looks like you are trying to reference here is Type 3: array($object, $method)
. But the same variable resolution happens. Now, ${$myclass}
is going to resolve differently, because the value of $myclass
is a Myclass Object. Variable names have to be strings, not objects (obviously), so ${Myclass Object}
is totally invalid.
$args=array($stringvar,1);
$retval=call_user_func_array(array(${$myclass}, 'myFunction'), $args);
But since $myclass at that point is an object already, you can just do the following (as mentioned initially above):
$retval=call_user_func_array(array($myclass, 'myFunction'), $args);
PHP calling class function dynamically by variables caughts exception
Check out this other reply: OOP in PHP: Class-function from a variable? (cannot comment, sorry...)
Anyway, this is what you are after: http://php.net/manual/en/functions.variable-functions.php
<?php
class Foo
{
function Variable()
{
$name = 'Bar';
$this->$name(); // This calls the Bar() method
}
function Bar()
{
echo "This is Bar";
}
}
$foo = new Foo();
$funcname = "Variable";
$foo->$funcname(); // This calls $foo->Variable()
?>
So I guess the only thing missing is the "()" after
$response1->$action;
Call method of static class with string name
You can directly call your Model Class in function.
public function get($page,$id,$seo_title)
{
$view_arg = null;
if($id)
{
$model = "App\\" . "tbl_$page"."s";
$view_arg = $model::whereId($id)->first();
}
}
Creating PHP class instance with a string
Yes, you can!
$str = 'One';
$class = 'Class'.$str;
$object = new $class();
When using namespaces, supply the fully qualified name:
$class = '\Foo\Bar\MyClass';
$instance = new $class();
Other cool stuff you can do in php are:
Variable variables:
$personCount = 123;
$varname = 'personCount';
echo $$varname; // echo's 123
And variable functions & methods.
$func = 'my_function';
$func('param1'); // calls my_function('param1');
$method = 'doStuff';
$object = new MyClass();
$object->$method(); // calls the MyClass->doStuff() method.
Call a variable function using a class property as function name
You need to implement a magic __call
method, like this:
class C
{
private $prop = "execute";
public function __call($method, $args)
{
if($method == "prop") // just for this prop name
{
if(method_exists($this, $this->prop))
return call_user_func_array([$this, $this->prop], $args);
}
}
public function execute ($s){
echo '>>'.$s.'<<';
}
}
$c = new C;
$c->prop(123);
Related Topics
Difference Between Eloquent\Model::Get() and All()
Php: Catch Exception and Continue Execution, Is It Possible
How to Store JavaScript Variable Output into a PHP Variable
PHP Soap Client for Uk Mail Webservice API
How to Tell If a Timezone Observes Daylight Saving at Any Time of the Year
Running Imagemagick on Xampp 1.8.3 with Windows 7
Utf-8 Special Characters Not Displaying
Sort Xml via Attribute Value PHP
Php: How to Generate a Hmacsha256 Signature of a String
PHP How to Create Multiple Sessions
Php: Check Who Had Read Sent Email
Automatically Refresh Token Using Google Drive API with PHP Script
Remotely Connecting to a MySQL Database
Woocommerce - How to Create Multiple Single Product Template Based on Category