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
Related
I am playing around with this:
$sort = array('t1','t2');
function test($e){
echo array_search($e,$sort);
}
test('t1');
and get this error:
Warning: array_search(): Wrong datatype for second argument on line 4
if I call it without function like this, I got the result 0;
echo array_search('t1',$sort);
What goes wrong here?? thanks for help.
Variables in PHP have function scope. The variable $sort is not available in your function test, because you have not passed it in. You'll have to pass it into the function as a parameter as well, or define it inside the function.
You can also use the global keyword, but it is really not recommended. Pass data explictly.
You must pass the array as a parameter! Because the functions variables are different from globals in php!
Here is the fixed one:
$sort = array('t1','t2');
function test($e,$sort){
echo array_search($e,$sort);
}
test('t2',$sort);
You cannot directly access global variables from inside functions.
You have three options:
function test($e) {
global $sort;
echo array_search($e, $sort);
}
function test($e) {
echo array_search($e, $GLOBALS['sort']);
}
function test($e, $sort) {
echo array_search($e, $sort);
} // call with test('t1', $sort);
take the $sort inside the function or pass $sort as parameter to function test()..
For e.g.
function test($e){
$sort = array('t1','t2');
echo array_search($e,$sort);
}
test('t1');
----- OR -----
$sort = array('t1','t2');
function test($e,$sort){
echo array_search($e,$sort);
}
test('t1',$sort);
I am trying to do something like this:
//function name
$str = 'bla()';
//make function with string as name
function $str{
echo 'yey';
}
//Call the function by string name
bla();
You could use eval() to attempt this task. But I really do NOT suggest it:
// name of the function
$str = 'bla';
// php code you want to execute inside
$inside = '';
eval("
function $str() { $inside }
");
Or you could also use an anonymous function:
$name = function() {
// code
};
// execution
$name();
Als if you are just trying to call a dynamic function just use call_user_func() like this:
// name of the function
$str = 'bla';
// paramters to the function
$param = array();
call_user_func($str, $param);
But I think you are doing something wrong. This kind of "hacks" are sign of bad application architecture.
References
eval()
call_user_func()
Anonymous functions
I'll suggest you, not to use like this. But if still you want to do this,
<?php
$greet = function($name)
{
printf("Hello %s\r\n", $name);
};
$greet('World');
$greet('PHP');
?>
Check here
And you are required to use PHP 5.3
Whenever a function completes, it RETURNS a value. If no value is set to be returned, 0 is returned.
If you would like to be able to do as you have asked, you could do the following:
function blah($string="Blah"){
return($string);
}
echo blah("Banana"); //echo's Banana
echo blah(); //echo's Blah
$str = blah("Apple"); //Sets $str to Apple
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...
});
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);
}
I have a function to send mail to users and I want to pass one of its parameter as an array of ids.
Is this possible to do? If yes, how can it be done?
Suppose we have a function as:
function sendemail($id, $userid) {
}
In the example, $id should be an array.
You can pass an array as an argument. It is copied by value (or COW'd, which essentially means the same to you), so you can array_pop() (and similar) all you like on it and won't affect anything outside.
function sendemail($id, $userid){
// ...
}
sendemail(array('a', 'b', 'c'), 10);
You can in fact only accept an array there by placing its type in the function's argument signature...
function sendemail(array $id, $userid){
// ...
}
You can also call the function with its arguments as an array...
call_user_func_array('sendemail', array('argument1', 'argument2'));
even more cool, you can pass a variable count of parameters to a function like this:
function sendmail(...$users){
foreach($users as $user){
}
}
sendmail('user1','user2','user3');
Yes, you can safely pass an array as a parameter.
Yes, you can do that.
function sendemail($id_list,$userid){
foreach($id_list as $id) {
printf("$id\n"); // Will run twice, once outputting id1, then id2
}
}
$idl = Array("id1", "id2");
$uid = "userID";
sendemail($idl, $uid);
What should be clarified here.
Just pass the array when you call this function.
function sendemail($id,$userid){
Some Process....
}
$id=array(1,2);
sendmail($id,$userid);
function sendemail(Array $id,$userid){ // forces $id must be an array
Some Process....
}
$ids = array(121,122,123);
sendmail($ids, $userId);
Its no different to any other variable, e.g.
function sendemail($id,$userid){
echo $arr["foo"];
}
$arr = array("foo" => "bar");
sendemail($arr, $userid);
I composed this code as an example. Hope the idea works!
<?php
$friends = array('Robert', 'Louis', 'Ferdinand');
function greetings($friends){
echo "Greetings, $friends <br>";
}
foreach ($friends as $friend) {
greetings($friend);
}
?>
I found Delcon answer helpful but I was looking for this
function sendmail($user1, $user2, $user3){
echo $user1;
echo $user2;
echo $user3;
}
$users = array('user1','user2','user3');
sendmail(...$users);
In php 5, you can also hint the type of the passed variable:
function sendemail(array $id, $userid){
//function body
}
See type hinting.
Since PHP is dynamically weakly typed, you can pass any variable to the function and the function will try to do its best with it.
Therefore, you can indeed pass arrays as parameters.
Yes, we can pass arrays to a function.
$arr = array(“a” => “first”, “b” => “second”, “c” => “third”);
function user_defined($item, $key)
{
echo $key.”-”.$item.”<br/>”;
}
array_walk($arr, ‘user_defined’);
We can find more array functions here
http://skillrow.com/array-functions-in-php-part1/
<?php
function takes_array($input)
{
echo "$input[0] + $input[1] = ", $input[0]+$input[1];
}
?>