Is there a way I can include(?) one function into another? For example, the same way we can include files using include function.
Thank you.
<?php
class test{
public function message1(){
$message = 'i am in message1 function';
return $message;
}
public function message2(){
$message = $this->message1();
echo $message;
}
}
Functions can not be "included" like you mean but you can call them and use their returned values to other functions like below.
Now if you try to call the message2 function using something like:
$messageClass = new test();
echo $messageClass->message2();
you will see that the output is the $message from function message1
Do you mean callback function? If so, this is how to use it:
// This is callback function which will passed as argument to another function.
function callbackFunction1 ($str) {
return strtoupper($str);
}
function mainFunction ($offeredCallback, $str) {
echo( "(" . $offeredCallback($str) . ")<br>");
}
mainFunction("callbackFunction1", "foo");
// Output "(foo)".
// If you want to use Variable Function, define it like this:
$callbackFunction2 = function ($str) {
return strtoupper($str);
};
mainFunction($callbackFunction2, "bar");
// Output "(bar)".
About Variable Function, see Anonymous Function.
Related
I would like to know how I can dynamically execute a method in my class using the following string.
$model = "Shop\Cart\Models\Cart#getInfo";
my idea is to save this command in the database, and then dynamically call the command and get the data return..
My difficulty is how to execute this command, is it possible?
An alternative I did is to explode the # and then use the call_user_func method, but I would like to know if there is any way without using explodes and making the request directly.
Define classname first
$className = 'Shop\Cart\Models\Cart';
Then call the method
(new $className())->getInfo();
You can make a function which can extract class and method name and call afterwards.
<?php
$model = "Cart#getInfo";
function make($str) {
$a = explode("#", $str);
$c = new $a[0];
return $c->{$a[1]}();
}
class Cart {
public function getInfo() {
return "Hello World";
}
}
$res = make($model);
print_r($res);
output
// Hello World
Try to use eval()
<?php
require_once './Classes/MyClasses.php';
function e($string)
{
$string = str_replace('#', '::', $string);
return eval($string . '();');
}
$a = e('Classes\MyClasses\MyClass#test'); // test
?>
file ./Classes/MyClasses.php contains next:
<?php
namespace Classes\MyClasses;
class MyClass
{
public static function test()
{
echo 'test';
}
}
?>
I have a class containing a lot of "return" functions :
Class Components_superclass
{
public function build()
{
$this->add_category('Grille');
}
public function add_category($name)
{
return '<div class="category">'. $name .'</div>';
}
...
}
I want to get the html code containing in "add_category" function. But when I echo this, I have nothing :
$component = new Components_superclass();
echo $component->build();
Must I add "return" in build function ? Is there a way to avoid this ? Because I have a lot of function to call and I don't want to write something like this :
public function build()
{
return
$this->function_1() .
$this->function_2() .
$this->function_3();
}
Thanks !
Yes, the echo doesn't work because nothing is returned from build – there is not string that's passed into echo which could be printed.
About your second question, you could buffer the string internally and then return it at once, like this:
Class Components_superclass
{
private $buffer = array();
// …
public function add_category($name)
{
$this->buffer[] = '<div class="category">'. $name .'</div>';
}
public function output()
{
return implode('', $this->buffer);
}
}
If you want a function to return a value (that can be a string, integer or other types) use return. If you call the function, the returned value is then available on that place.
If function_1() return the string 'I am function one' and you echo the function call (echo $this->function_1();), the string 'I am function one' will be echoed.
This is also the correct way of working with functions. If you want to echo thing from inside the function, just echo in the function.
Check out PHP.net's function documentation!
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Use a variable to define a PHP function
Use Variable as Function Name in PHP
I want to perform a conditional function call but I don't necessarily know what what the function will be, so that would be a long switch.
For example;
$userSelection = "calculator"; /* or "stocks" or whatever widget */
$widget->get_widget($userSelection);
public function __construct($userSelection){
/* pseudo code */
call function $userSelection();
}
public function calculator(){
/* Get Calculator */
}
Sure there is. This feature is called variable functions:
$functionName = "strlen";
$length = $$functionName("Hello world!");
The $$var(...) syntax is convenient, but it will only work with free functions. If you want to call a class method this way, you will need to use call_user_func or call_user_func_array (these functions can also handle the "free function" case).
Look at the call-user-func function. This allows you to call another function, e.g.
call_user_func('calculator')
call_user_func($userSelection);
http://php.net/manual/en/function.call-user-func.php
Take a look at this php functions:
call_user_func(): http://php.net/manual/de/function.call-user-func.php
call_user_func_array(): http://www.php.net/manual/de/function.call-user-func-array.php
create_function(): http://www.php.net/manual/de/function.create-function.php
There is also a direct (though ugly) execution syntax:
function some_func(args) {...}
$function_name='some_func';
$$function_name(args2);
You can use call_user_func() for that, like this:
$userSelection = "calculator";
call_user_func($userSelection[, $param1, $param2, ...]);
call_user_func_array($userSelection, $params);
If it's just a function you're after then using this should solve your problems
$function = "echo";
$$function "fooBar";
If it's a class method that you want to keep flexible use magic method __call() which will allow you to use method names that are not pre-defined.
__call() is triggered when invoking inaccessible methods in an object context.
i.e.
class Foo {
public function __call($name, $arguments) {
echo $name;
}
}
$foo = new Foo();
$foo->bar(); // will echo "bar"
PHP built-in function 'eval' can do everything, but beware of injection.
$var = "somefunction";
eval("$var();");
http://php.net/manual/en/function.eval.php
It's pretty simple if that's what you mean.
function calculator() {
echo 'foo';
}
$userSelection = "calculator";
if (function_exists($userSelection)) {
$userSelection();
}
Or within a class like in your example:
class widget {
public function __construct($userSelection) {
echo 'constructed widget<br>';
if (function_exists($userSelection)) {
$this->$userSelection();
}
}
public function calculator() {
echo 'bar';
}
}
$userSelection = "calculator";
$widget = new widget($userSelection);
Or from outside a class when the function is part of the class.
class widget {
public function calculator() {
echo 'bar';
}
}
$widget = new widget();
$userSelection = "calculator";
$widget->$userSelection();
I would work with if/else statements though to determine the function to be called just to be sure that only valid functions are executed (do you sanitize the user selection or do you just get it from a $_POST? The latter would be a very bad idea).
You can do following :
$var = 'abc';
switch ($var) {
case 'abc':
$result = $var('test param');
echo $result;
break;
default :
echo 'default';
break;
}
function abc($data) {
return $data;
}
I have a variable like $string = "blah";
How can I create a function that has the variable value as name?
Is this possible in PHP?
Like function $string($args){ ... } or something, and be able to call it like:
blah($args);
this might not be a good idea, but you can do something like this:
$string = "blah";
$args = "args"
$string = 'function ' . $string . "({$args}) { ... }";
eval($string);
That doesn't sound like a great design choice, it might be worth rethinking it, but...
If you're using PHP 5.3 you could use an anonymous function.
<?php
$functionName = "doStuff";
$$functionName = function($args) {
// Do stuff
};
$args = array();
$doStuff($args);
?>
Okay, challenge accepted!
No matter how weird the question is (it's not btw), let's take it seriously for a moment! It could be useful to have a class that can declare functions and make them real:
<?php
customFunctions::add("hello", // prepare function "hello"
function($what) {
print "Hello $what, as Ritchie said";
print "<br>";
}
);
customFunctions::add("goodbye", // prepare function "goodbye"
function($what,$when) {
print "Goodbye cruel $what, ";
print "I'm leaving you $when";
print "<br>";
}
);
eval(customFunctions::make()); // inevitable - but it's safe!
That's it! Now they're real functions. No $-prefixing, no runtime evaluations whenever they get called - eval() was only needed once, for declaration. After that, they work like any function.
Let's try them:
hello('World'); // "Hello World"
goodbye('world','today'); // "Goodbye cruel world, I'm leaving you today"
Magic behind
Here's the class that can do this. Really not a complex one:
class customFunctions {
private static $store = [];
private static $maker = "";
private static $declaration = '
function %s() {
return call_user_func_array(
%s::get(__FUNCTION__),
func_get_args()
);
}
';
private static function safeName($name) {
// extra safety against bad function names
$name = preg_replace('/[^a-zA-Z0-9_]/',"",$name);
$name = substr($name,0,64);
return $name;
}
public static function add($name,$func) {
// prepares a new function for make()
$name = self::safeName($name);
self::$store[$name] = $func;
self::$maker.=sprintf(self::$declaration,$name,__CLASS__);
}
public static function get($name) {
// returns a stored callable
return self::$store[$name];
}
public static function make() {
// returns a string with all declarations
return self::$maker;
}
}
It provides an inner storage for your functions, and then declare "real" functions that call them. This is something similar to fardjad's solution, but with real code (not strings) and therefore a lot more convenient & readable.
Try call_user_func_array()
php.net link
You can call a function by its name stored in a variable, and you can also assign a function to variables and call it using the variable. If it's not what you want, please explain more.
How to pass a $_GET variable into function?
$_GET['TEST']='some word';
public function example() {
//pass $_GET['TEST'] into here
}
When I try to access $_GET['TEST'] in my function, it is empty.
The $_GET array is one of PHPs superglobals so you can use it as-is within the function:
public function example() {
print $_GET['TEST'];
}
In general, you pass a variable (argument) like so:
public function example($arg1) {
print $arg1;
}
example($myNonGlobalVar);
If this is a function and not an object method then you pass the parameter like so
function example($test) {
echo $test;
}
and then you call that function like so
$_GET['test'] = 'test';
example($_GET['test']);
output being
test
However if this is an object you could do this
class Test {
public function example($test) {
echo $test;
}
}
and you would then call it like so
$_GET['test'] = 'test';
$testObj = new Test;
$testObj->example($_GET['test']);
and the output should be
test
I hope this helps you out.
First of all - you should not set anything to superglobals ($_GET, $_POST, etc).
So we convert it to:
$test = 'some word';
And if you want to pass it to the function just do something like:
function example($value) {
echo $value;
}
And call this function with:
example($test);
function example ($value) {
$value; // available here
}
example($_GET['TEST']);
function example($parameter)
{
do something with $parameter;
}
$variable = 'some word';
example($variable);
Simply declare the value for the variable by
declare the function by
function employee($name,$email) {
// function statements
}
$name = $_GET["name"];
$email = $_GET["email"];
calling the function by
employee($name,$email);