Following a Tutorial I am struggling with an issue in a PHP function. I have some basic background on C# and Java and according to my knowledge this code shouldn't work since I am not passing any parameter in the add() function, but , surprisingly!, it works!
According to PHP Manual the func_num_args() Gets the number of arguments passed to the function.so how we can echo the result of the add() function while we are not passing any parameter in the function?! Also, if the function is for getting the number of arguments how we can use it to calculate the numbers?!
<?php
function add(){
$args = func_num_args();
$sum = 0;
$i = 0;
for($i; $i< $args; $i++ ){
is_int(func_num_args($i)) ? $sum+= func_num_args($i) : die('Use Only Numbers');
}
}
echo add(2,5,10,12);
?>
Thanks for your comments
Use func_get_args():
function add(){
if(!func_num_args())return 0;
$args = func_get_args();
$sum = 0;
foreach($args as $arg){
if(is_int($arg)){
$sum += $arg;
} else {
die('Use Only Numbers');
}
}
return $sum;
}
As I mentioned in comments for "no args" case:
func_num_args()s return value is 0. for-loop in your code will not work as of $i < $args simplifies to 0 < 0, which is false.
To prevet that, you may try to use:
if(!func_num_args()){
die('There are no args!');
}
Your line echo add(); will work anyway, because:
PHP has support for variable-length argument lists in user-defined
functions. This is really quite easy, using the func_num_args(),
func_get_arg(), and func_get_args() functions.
No special syntax is required, and argument lists may still be
explicitly provided with function definitions and will behave as
normal.
Use func_get_args()
func_num_args()s return value is 0. for-loop in your code will not work as of $i < $args simplifies to 0 < 0, which is false.
To prevet that, you may try to use:
if(!func_num_args()){
die('There are no args!');
}
I think you are confused because you know what function overloading is, but php does not support function overloading in this manner.
Please go through this link. It will really help you out of your confusion.
php function overloading
Related
My problem is that I have lots of functions with VERY long lists of function parameters such as this one:
function select_items($con,$type,$id_item,$item_timestamp,$item_source_url,$item_type,$item_status,$item_blogged_status,$item_viewcount,$item_language,$item_difficulty,$item_sharecount,$item_pincount,$item_commentcount,$item_mainpage,$item_image_width,$item_image_height,$item_image_color,$item_modtime,$order,$start,$limit,$keyword,$language,$id_author,$id_sub_category,$id_category,$id_tag,$id_user){ ... }
As you can see its super long and (of course) very hard to maintain. Sometimes I need all of the variables to construct a super complex sql query, but sometimes I just use 1 or 2 of them. Is there a way to avoid this colossal list of parameters? For example with some strict / special naming convention ?
So basically I need something like this:
$strictly_the_same_param_name="It's working!";
echo hello($strictly_the_same_param_name);
function hello() //<- no, or flexible list of variables
{
return $strictly_the_same_param_name; // but still able to recognize the incoming value
}
// outputs: It's working!
I thought about using $_GLOBALs / global or $_SESSIONs to solve this problem but it doesn't seems really professional to me. Or is it?
For a first step, as you said, sometimes you need to call the function with only 2 args, you can set default values to your arguments in the declaration of your function. This will allow you to call your function with only 2 args out of 25.
For example:
function foo($mandatory_arg1, $optional_arg = null, $opt_arg2 = "blog_post") {
// do something
}
In a second step, you can use, and especially for that case, arrays, it will be way more simple:
function foo(Array $params) {
// then here test your keys / values
}
In a third step, you can also use Variable-length argument lists (search in the page "..."):
function sum(...$numbers) {
$acc = 0;
foreach ($numbers as $n) {
$acc += $n;
}
return $acc;
}
But ultimately, I think you should use objects to handle such things ;)
You can try use ... token:
$strictly_the_same_param_name= ["It's working!"];
echo hello($strictly_the_same_param_name);
function hello(...$args) //<- no, or flexible list of variables
{
if ( is_array( $args ) {
$key = array_search( 'What you need', $args );
if ( $key !== false ) {
return $args[$key];
}
}
return 'Default value or something else';
}
I need to build a method column which can called with different arguments type, such like the situation here .
->column('herald','style')
->column('herald','style','styleText')
->column('herald',['kind','style'])
->column('herald',['kind','style'],['kindText','styleText'])
->column('item',['kind','style'],false)
->column('item',['kind','style'],['kindText','styleText'],false)
->column('herald_style','style',false)
->column('herald_style','style','styleText',false)
I just want the function can be called clearly ,to overwrite like the Java do, and I have been tried using the func_get_args() to handle the arguments one by one, but it`s seem worse..
Is that have any way to do ?
Accepting a variable number of arguments in a function?
If using PHP 5.6+ you can use the splat operator ... to put any submitted arguments into an array.
function column(...$args) {
// this is how many arguments were submitted
$number_of_arguments = count($args);
// iterate through them if you want...
foreach($args as $arg) {
// ...and process the arguments one by one
do_something_with($arg);
}
}
See example 13 on http://php.net/manual/en/functions.arguments.php
If using an earlier version of PHP then Sanjay Kumar N S's answer will do it.
If you mean ['kind','style'] as an array, then try this:
<?php
function column()
{
$numargs = func_num_args();
$arg_list = func_get_args();
for ($i = 0; $i < $numargs; $i++) {
echo "Argument $i is: " . (!is_array($arg_list[$i]) ? $arg_list[$i]: ' an array ' ). "<br />";
}
echo "<br /><br />";
}
column('herald','style');
column('herald','style');
column('herald','style','styleText');
column('herald',array('kind','style'));
column('herald',array('kind','style'),array('kindText','styleText'));
column('item',array('kind','style'),false);
column('item',array('kind','style'),array('kindText','styleText'),false);
column('herald_style','style',false);
column('herald_style','style','styleText',false);
?>
You can use func_get_args() at body of your function like this:
function callMe() {
dd(func_get_args());
}
Also if it depends on count of arguments you can use func_num_args()
http://php.net/manual/ru/function.func-get-args.php
How would I go about writing a function in php with an unknown number of parameters, for example
function echoData (parameter1, parameter2,) {
//do something
}
But when you call the function you can use:
echoData('hello', 'hello2', 'hello3', 'hello'4);
So that more parameters can be sent as the number of parameters will be unknown.
Just for those who found this thread on Google.
In PHP 5.6 and above you can use ... to specify the unknown number of parameters:
function sum(...$numbers) {
$acc = 0;
foreach ($numbers as $n) {
$acc += $n;
}
return $acc;
}
echo sum(1, 2, 3, 4); // 10
$numbers is an array of arguments.
func_get_args()
function echoData(){
$args = func_get_args();
}
Be aware that while you can do it, you shouldn't define any arguments in the function declaration if you are going to use func_get_args() - simply because it gets very confusing if/when any of the defined arguments are omitted
Similar functions about arguments
func_get_arg()
func_get_args()
func_num_args()
use func_get_args() to retrieve an array of all parameters like that:
$args = func_get_args();
You can then use the array or iterate over it, whatever suits your use-case best.
You can also use an array:
<?php
function example($args = array())
{
if ( isset ( $args["arg1"] ) )
echo "Arg1!";
}
example(array("arg1"=>"val", "arg2"=>"val"));
I am trying to create a PHP function that takes another PHP function as input. Here is an example:
function getMean(function){
$allUsers = getAllUsers();
$sum = 0;
foreach ($allUsers as $currentUser ){
$sum =+ (function($currentUser['CONSUMER_ID'], 5, 8))/(8-5);
}
}
Perhaps something like this should do it. PHP has a "type" called callback, which can be a closure (as of PHP 5.3), name of a function or array containing object and the method to call. These callbacks can be called with call_user_func()
function getMean($callback){
$allUsers = getAllUsers();
$sum = 0;
foreach ($allUsers as $currentUser ){
$sum =+ (call_user_func($callback, $currentUser['CONSUMER_ID'], 5, 8))/(8-5);
}
return $sum;
}
You need PHP 5.3 to do that natively.
function getMean($function){
$allUsers = getAllUsers();
$sum = 0;
foreach ($allUsers as $currentUser ){
$sum += ($function($currentUser['CONSUMER_ID'], 5, 8))/(8-5);
}
return $sum;
}
getMean(function($consumer_id, $five, $eight) {
return $consumer_id;
});
I you run PHP 5.3- (lower than 5.3), you need to use a callback (documentation is here) along with the call_user_func() or call_user_func_array() function.
you can do that as long as function($currentUser['CONSUMER_ID'], 5, 8) returns something
It looks like the PHP Eval function is what you are looking for. Pass the getMean function a string, and then change the line to have $sum =+ (eval($param) .....)
Security is a problem though because any function can be passed.
Save the function as a variable.
$function = function($param1){ //code here }
and pass it to your other function as a parameter.
function getMean($function)
{
//code here
$sum += $function($param);
}
[edit]
PHP.net Manual - Variable Functions
are you searching for anonymous functions?
Felix
If you want to dynamically create a function in php < 5.3 then youre stuck with using create_function. Becuase of how you use this function its really insane to use it for anything but but creating simple function for array_map,array_walk or things that do simple calculations or basic text processing.
If youre doing anything more complex than that its much easier and less of a headache to simply define the function as normal and then use it with call_user_func or call_user_func_array as others have suggested.
DO NOT USE eval :-)
I have two functions like this:
function mysql_safe_query($format) {
$args = array_slice(func_get_args(),1);
$args = array_map('mysql_safe_string',$args);
$query = vsprintf($format,$args);
$result = mysql_query($query);
if($result === false) echo '<div class="mysql-error">',mysql_error(),'<br/>',$query,'</div>';
return $result;
}
function mysql_row_exists() {
$result = mysql_safe_query(func_get_args());
return mysql_num_rows($result) > 0;
}
The problem is that the second function won't work because it passes the args to the first one as an array, when it expects them as different parameters. Is there any way to get around this, preferably without modifying mysql_safe_query?
How about using:
$args = func_get_args();
call_user_func_array('mysql_safe_query', $args);
N.B. In PHP 5.6 you can now do this:
function mysql_row_exists(...$args) {
$result = mysql_safe_query(...$args);
return mysql_num_rows($result) > 0;
}
Also, for future readers, mysql_* is deprecated -- don't use those functions.
Depending on the situation, following might also work for you and might be a little faster.
function mysql_safe_query($format) {
$args = func_get_args();
$args = is_array($args[0]) ? $args[0] : $args; // remove extra container, if needed
// ...
Which now allows for both types of calling, but might be problematic if your first value is supposed to be an actual array, because it would be unpacked either way.
You could additionally check on the length of your root-array, so it might not be unpacked if if there are other elements, but as mentioned: It is not really that "clean" in general, but might be helpful and fast :-)