I have a function variable like this...
$aName = "My Name";
$sayHelloFunction = public function sayHello($aName){
echo($aName);
}
and I have something like this.....
callAFunctionFromFunction($sayHelloFunction);
Inside the "callAFunctionFromFunction", I do this:
if(is_callable($sayHelloFunction)) {
$sayHelloFunction();
}
I found that the "My Name" can't display, what did I do wrong...
I suggest you to look here and here as these exact threads deal with passing a function as a parameter. Also closures (anonymous functions) in PHP have no name (that's why they are called anonymous), so what you should do is something like that.
<?php $sayHelloFunction = function($aName){
echo($aName);
};
if(is_callable($sayHelloFunction)) $sayHelloFunction("Testing 1,2,3");
The function sayHello expects a parameter $aName, but when you call it you don't pass in a value.
You would need to do this:
if(is_callable($sayHelloFunction)) {
$sayHelloFunction("Hello John");
}
Also you can't use the public access type with closures.
$sayHelloFunction = function sayHello($aName) {
echo($aName);
}
Related
In codeigniter what is the correct method of passing variables to the callback function?
I have used this,
$var1 = 'some conditions';
$this->form_validation->set_rules("callback__is_value_unique[value, $var1]");
public function _is_value_unique($value, $var1){
echo $var1;
die;
}
This gave me output like shown below:-
value, some conditions
rather than,
some conditions
You must only set your value!
$var1 = 'some conditions';
$this->form_validation->set_rules("callback__is_value_unique[value, $var1]");
public function _is_value_unique($value, $var1){
echo $var1;
die;
}
From the docs..
If you need to receive an extra parameter in your callback function,
just add it normally after the function name between square brackets,
as in: "callback_foo[bar]", then it will be passed as the second
argument of your callback function.
Sounds like you could only pass one extra argument. Which should be a string. If you want to pass more arguments, you could store them somewhere else and just pass an argument, which stores the location of the additional param.
$index = count($this->arguments);
$this->arguments[$index] = array('value', 'some conditions'/*, ...*/);
$this->form_validation->set_rules("callback__is_value_unique[$index]");
public function _is_value_unique($value, $index){
$args = $this->argumts[$index];
echo $args[1];
die;
}
I am using this code (note: HELLO_WORLD was NEVER defined!):
function my_function($Foo) {
//...
}
my_function(HELLO_WORLD);
HELLO_WORLD might be defined, it might not. I want to know if it was passed and if HELLO_WORLD was passed assuming it was as constant. I don't care about the value of HELLO_WORLD.
Something like this:
function my_function($Foo) {
if (was_passed_as_constant($Foo)) {
//Do something...
}
}
How can I tell if a parameter was passed assuming it was a constant or just variable?
I know it's not great programming, but it's what I'd like to do.
if a constant isn't defined, PHP will treat it as String ("HELLO_WORLD" in this case) (and throw a Notice into your Log-files).
You could do a check as follows:
function my_function($foo) {
if ($foo != 'HELLO_WORLD') {
//Do something...
}
}
but sadly, this code has two big problems:
you need to know the name of the constant that gets passed
the constand musn't contain it's own name
A better solution would be to pass the constant-name instead of the constant itself:
function my_function($const) {
if (defined($const)) {
$foo = constant($const);
//Do something...
}
}
for this, the only thing you have to change is to pass the name of a constant instead of the constant itself. the good thing: this will also prevent the notice thrown in your original code.
You could do it like this:
function my_function($Foo) {
if (defined($Foo)) {
// Was passed as a constant
// Do this to get the value:
$value = constant($Foo);
}
else {
// Was passed as a variable
$value = $Foo;
}
}
However you would need to quote the string to call the function:
my_function("CONSTANT_NAME");
Also, this will only work if there is no variable whose value is the same as a defined constant name:
define("FRUIT", "watermelon");
$object = "FRUIT";
my_function($object); // will execute the passed as a constant part
Try this:
$my_function ('HELLO_WORLD');
function my_function ($foo)
{
$constant_list = get_defined_constants(true);
if (array_key_exists ($foo, $constant_list['user']))
{
print "{$foo} is a constant.";
}
else
{
print "{$foo} is not a constant.";
}
}
I would like to do something like this:
function readUser($aUser = loadDefaultUser()){
//doing read User
}
I find that it will display a error to me, how can I pass a function return as a default value? Thank you.
I would rather give a Null value for this argument and then call loadDefaultUser() in the body of the function. Something like this:
function readUser($aUser = NULL){
if(is_null($aUser)){
$aUser = loadDefaultUser();
}
//...
}
Yes, you can provide a default argument. However, the default argument "must be a constant expression, not (for example) a variable, a class member or a function call."
You can fake this behaviour by using some constant value for the default, then replacing it with the results of a function call when the function is invoked.
We'll use NULL, since that's a pretty typical "no value" value:
function readUser($aUser = NULL) {
if (is_null($aUser))
$aUser = loadDefaultUser();
// ... your code here
}
You can add a callback-parameter to your loadDefaultUser() function when it's finished it fires the callback function with the return/result. It's a bit like ajax-javascript callbacks.
function loadDefaultUser ( $callback )
{
$result = true;
return $callback($result);
}
function readUser($aUser = NULL){
if ($aUser === NULL){
$aUser = loadDefaultUser();
}
//do your stuff
}
I have a function variable like this...
$aName = "My Name";
The function need to pass in like this:
$sayHelloFunction = function sayHello($aName){
echo($aName);
}
Than, I have a method that responsible for execute the sayHelloFunction:
runningFunction($sayHelloFunction($aName));
in the runningFunction, it will have some condition to execute the function, but when I pass the "$sayHelloFunction($aName)" to runningFunction, it execute automatically, but I would like to pass the variable $aName as well, how can I achieve it? Thank you.
runningFunction($sayHelloFunction, $aName);
Simples.
You will have to pass the arguments separately. However, you could wrap them in an array so that you can pass them to runningFunction as a single argument, like this:
$printFunction = function($args) {
print $args['lastname'].', '.$args['firstname'];
};
function runningFunction($f, $a) {
$f($a);
}
$firstname = 'Bob';
$lastname = 'Smith';
$functionArguments = array(
'firstname' => $firstname,
'lastname' => $lastname
);
runningFunction($printFunction, $functionArguments);
If you want your dynamic functions to get "proper" arguments, then I see no way around something like this:
function runningFunction($f, $a) {
switch(count($a)) {
0: $f(); break;
1: $f($a[0]); break;
2: $f($a[0], $a[1]); break;
3: $f($a[0], $a[1], $a[2]); break;
// and so on
}
}
Pass the parameters as an array, and then use call_user_func_array() to call your function.
This way your runningFunction() will be absolutely abstract (as you requested), it can call any type of function, it's your responsibility to pass the right number of parameters.
function runningFunction ($callback, $parameters=array()) {
call_user_func_array($callback, $parameters);
}
runningFunction($sayHelloFunction, array($aName));
call_user_func_array()
as xconspirisist suggested pass $aName as a seperate parameter to the function.
Details on Variable Functions can be found on the PHP site.
Use an anonymous function when calling runningFunction
function runningFunction($func) {
$func();
}
runningFunction(function() {
$sayHelloFunction($aName));
// You can do more function calls here...
});
How to write a php function in order to pass parameters
like this
student('name=Nick&roll=1234');
If your format is URL encoded you can use parse_str to get the variables in your functions scope:
function student($args)
{
parse_str($args);
echo $name;
echo $roll;
}
Although, if this string is the scripts URL parameters you can just use the $_GET global variable.
Pass parameters like this:
student($parameter1, $parameter2){
//do stuff
return $something;
}
call function like this:
student($_GET['name'], $_GET['roll']);
Use parse_str.
function foo($paraString){
try{
$expressions = explode('&',$paraString);
$args = array();
foreach($expressions as $exoression){
$kvPair = explode('=',$exoression);
if(count($kvPair !=2))throw new Exception("format exception....");
$args[$kvPair[0]] = $kvPair[1];
}
....
Edit: that wayyou can do it manually. If you just want to get something out of a querrystring there are already functions to get the job done