I know you can use func_num_args to get the number of actual arguments passed in. Is there any way to get the number of formal parameters?
Example:
<?php
function optional($a, $b = null) {
echo func_num_args();
}
optional(1); // 1
optional(1, 1); // 2
optional(1, 1, 1); // 3
I want a way to get 2 in each of those calls to optional, without hard-coding it.
One way is with ReflectionFunction, e.g.:
function optional($a, $b = null) {
return (new ReflectionFunction(__FUNCTION__))->getNumberOfParameters();
}
Related
First, let me start by saying i'm a real beginner learning mostly PHP. Understanding the patterns and semantics of programming is more important to me than just learning the syntax. I did some research for what I'm going to ask, but I couldn't find any info about it. So, I was thinking... What if I need to do the following... Give a function multiple outputs to pass in other parts of the code. What is the name of this type of functionality (if it exists)? Or If it doesn't exist, why not? And what is the best practice to achieve the same semantic?
More details:
Let's say I want to call a function with one argument and return not only the value back to that same argument call location, but also in another location or into some other part of the program. Meaning a function with two outputs in two different locations, but the second location wouldn't be a call, just an output from the call made in the first location, returned at the same time with the same value output as the first. So, not calling it twice separately... But rather calling once and outputting twice in different locations. The second output would be used to pass the result into another part of the program and therefore wouldn't be appropriate as a "call/input", but more as an "output" only from the "input" value. How can I achieve multiple outputs in functions?
If this seems like a stupid question, I'm sorry. I couldn't find the info anywhere. Thanks in advance
What you want to do is basically this (i'll make it a 'practical' example):
function add($number1, $number2)
{
$result = $number1 + $number2;
return array('number1' => $number1,'number2' => $number2,'result' => $result);
}
$add = add(5,6); // Returns array('number1' => 5, 'number2' => 6, 'result' => 11);
You now have the two arguments and the result of that function at your disposal to use in other functions.
some_function1($add['result']);
...
some_function2($add['number1']);
If the question is about returning more than one variables, it is simply:
function wtf($foobar = true) {
$var1 = "first";
$var2 = "second";
if($foobar === true) {
return $var2;
}
return $var1;
}
You can either have the function return an array of values:
function foo($bar) {
$bat = 1;
return [$bar, $bat];
}
Or you can pass an argument that tells it which value to return:
function foo($bar, $return_bar=false) {
$bat = 1;
return $return_bar ? $bar : $bat;
}
In php you can usually call a function with more parameters than have been defined, e.g.
function f($a, $b) {
return $a . $b;
}
f('a', 'b', 'c', 'e');
is totally valid.
I understand that you can define functions with a variable number of parameters. But in most cases that is not what you want to do.
So in these cases if you mistakenly replace a . by a , you will not even get warning.
$x = '0';
f('a' , 'b' . $x . 'c') // returns ab0c
f('a' , 'b' , $x . 'c') // returns ab
Now in PHP 7 there is the function f($a, $b, ...$others) syntax. So in princable it is possible to discern variable parameter functions from ordinary ones.
Is there a way to get a notice when a function is called with too many parameters?
There is a method of actually counting the variables sent to your function, however you can only do this INSIDE the function or BEFORE the function by counting the sent items.
See http://php.net/manual/en/function.func-num-args.php for more information.
You can also use http://php.net/manual/en/function.func-get-args.php to GET the current arguments sent to the function.
Your issue would however need something like this:
function(){
$count = func_num_args();
if($count > 3){
//too many args
}
else{
//continue your actual code
}
}
In C#, there is a new feature coming with 4.0 called Named Arguments and get along well with Optional Parameters.
private static void writeSomething(int a = 1, int b = 2){
// do something here;
}
static void Main()
{
writeSomething(b:3); // works pretty well
}
I was using this option to get some settings value from users.
In PHP, I cannot find anything similar except for the optional parameters but I am accepting doing $.fn.extend (jQuery) kind of function :
function settings($options)
{
$defaults = array("name"=>"something","lastname"=>"else");
$settings = array_merge($defaults,$options);
}
settigs(array("lastname"=>"John");
I am wondering what kind of solutions you are using or you would use for the same situation.
As you found out, named arguments don't exist in PHP.
But one possible solution would be to use one array as unique parameter -- as array items can be named :
my_function(array(
'my_param' => 10,
'other_param' => 'hello, world!',
));
And, in your function, you'd read data from that unique array parameter :
function my_function(array $params) {
// test if $params['my_param'] is set ; and use it if it is
// test if $params['other_param'] is set ; and use it if it is
// test if $params['yet_another_param'] is set ; and use it if it is
// ...
}
Still, there is one major inconvenient with this idea : looking at your function's definition, people will have no idea what parameters it expects / they can pass.
They will have to go read the documentation each time they want to call your function -- which is not something one loves to do, is it ?
Additionnal note : IDEs won't be able to provide hints either ; and phpdoc will be broken too...
You can get around that by having an array such as $array= array('arg1'=>'value1');
And then let the function accept the array such as function dostuff($stuff);
Then, you can check arguments using if(isset($stuff['arg1')){//do something.} inside the function itself
It's just a work-around but maybe it could help
You can fake C++-style optional arguments (i.e. all optional arguments are at the end) by checking for set variables:
function foo($a, $b)
{
$x = isset($a) ? $a : 3;
$y = isset($b) ? $b : 4;
print("X = $x, Y = $y\n");
}
#foo(8);
#foo();
It'll trigger a warning, which I'm suppressing with #. Not the most elegant solution, but syntactically close to what you wanted.
Edit. That was a silly idea. Use variadic arguments instead:
// faking foo($x = 3, $y = 3)
function foo()
{
$args = func_get_args();
$x = isset($args[0]) ? $args[0] : 3;
$y = isset($args[1]) ? $args[1] : 3;
print("X = $x, Y = $y\n");
}
foo(12,14);
foo(8);
foo();
I'm curious if I can assign a variable the value of a specific array index value returned by a function in PHP on one line.
Right now I have a function that returns an associative array and I do what I want in two lines.
$var = myFunction($param1, $param2);
$var = $var['specificIndex'];
without adding a parameter that determines what the return type is, is there a way to do this in one line?
In PHP 5.4, you can do this: $var = myFunction(param1, param2)['specificIndex'];.
Another option is to know the order of the array, and use list(). Note that list only works with numeric arrays.
For example:
function myFunction($a, $b){
// CODE
return array(12, 16);
}
list(,$b) = myFunction(1,2); // $b is now 16
You could add an additional optional parameter and, if set, would return that value. See the following code:
function myFunction($param1, $param2, $returnVal = "")
{
$arr = array();
// your code here
if ($returnVal)
{
return $arr[$returnval];
}
else
{
return $arr;
}
}
I have a question regarding PHP. Is there any way I could make a function, which has a dynamic number of function inputs?
For example, let's call that function dynamic_func()
It should work in both of these cases, and also in other cases, not depending on number of functions input:
dynamic_func(1,2,3,4)
dynamic_func(1,2,3,4,5,6)
Thanks in advance!
It works as normal.
function dynamic_func()
{
$args=func_get_args(); //get all the arguments as an array
}
dynamic_func(1,2,3,4); //will work
dynamic_func(1,2,3,4,5,6); //will work
I believe PHP will never complain if you pass more arguments than those expected by a function. E.g.:
<?php
function foo($a) {
}
foo(); // invalid (Warning: Missing argument 1 for ...)
foo('a'); // valid
foo('a', 'b'); // surprise... valid!
So you can use func_get_args() and func_num_args() inside foo() to detect how many parameters were actually passed on to that function:
<?php
function foo(/*$a*/) {
echo func_num_args();
var_dump(func_get_args());
}
foo('a', 'b');
Rest is up to you.
there are two possibilitys to do this: using func_get_args like Shakti Singh explained or predefine the arguments like this
function myfunc($arg1 = 1, $arg2 = 2, $arg3 = 3){
echo $arg1.' '.$arg1.' '.$arg3;
}
myfunc(); // outputs "1 2 3";
myfunc(9,8); // outputs "9 8 3";
note that you can set the arguments to any default value that is used if the argument isn't given, but you'll have to define all arguments with this - it isn't as dynamic as using func_get_args.