Here is the easiest way to call a Function, or Class method dinamically, with Name from a String, stored into a variable or array item.
-
Click on the code to select it.
1.
Calling function with name stored into a variable use:
$variable($parameters)
<?php
function url($adr){
return 'http://'. $adr;
}
// variable with function name
$fun = 'url';
// calls the functions with name from $fun
$val = $fun('coursesweb.net/php-mysql/');
echo $val; // https://coursesweb.net/php-mysql/
2.
Calling function with name stored into a string in array item use:
$array["key"]($parameters)
<?php
function getSum($x, $y){
return $x + $y;
}
function hi(){
echo 'Hello Friend';
}
// array with function names
$arr = ['f1'=>'getSum', 'f2'=>'hi'];
// calls the functions with name from $arr array
$sum = $arr['f1'](12, 89);
echo $sum; // 101
echo $arr['f2'](); // Hello Friend
3.
Calling class method with name from string in variable (add the variable with the method name within " {} "):
$object->{$variable}($parameter)
<?php
// PHP Class
class Cls {
// class method
public function site($str){
return 'http://'. $str;
}
}
// varible with method name
$method = 'site';
$obC = new Cls;
$val = $obC->{$method}('coursesweb.net/');
echo $val; // https://coursesweb.net/
4.
Calling class method with name from string in array item (add the array item with the method name within " {} "):
$object->{$array['key']}($parameters)
<?php
// PHP Class
class Cls {
// class methods
public function getSum($x, $y){
return $x + $y;
}
public function hi(){
return 'Hello Friend';
}
}
// array with method names
$mts = ['m1'=>'getSum', 'm2'=>'hi'];
$obC = new Cls;
$sum = $obC->{$mts['m1']}(12, 89);
$msg = $obC->{$mts['m2']}();
echo $sum; // 101
echo $msg; // Hello Friend
Daily Test with Code Example
HTML
CSS
JavaScript
PHP-MySQL
Which tag is used to add lists into <ul> and <ol> elements?
<dt> <dd> <li><ul>
<li>http://coursesweb.net/html/</li>
<li>http://coursesweb.net/css/</li>
</ul>
Which value of the "display" property creates a block box for the content and ads a bullet marker?
block list-item inline-block.some_class {
display: list-item;
}
Which instruction converts a JavaScript object into a JSON string.
JSON.parse() JSON.stringify eval()var obj = {
"courses": ["php", "javascript", "ajax"]
};
var jsonstr = JSON.stringify(obj);
alert(jsonstr); // {"courses":["php","javascript","ajax"]}
Indicate the PHP class used to work with HTML and XML content in PHP.
stdClass PDO DOMDocument$strhtml = '<body><div id="dv1">CoursesWeb.net</div></body>';
$dochtml = new DOMDocument();
$dochtml->loadHTML($strhtml);
$elm = $dochtml->getElementById("dv1");
echo $elm->nodeValue; // CoursesWeb.net