Convert each element in php array to separated parameter for function - php

Hie everyone am trying to pass the following array:
$cars=array("Volvo","BMW","Toyota");
To the following function
function foo(){
$numargs = func_num_args();
$args = func_get_args();
print_r($args);
}
What I want is to make each element in array to be separated element in $args
at the same time I don't to write the function and parameters like that way
foo($cars[0],$cars[1]);

<?php
for ($i=0; $i<sizeof($array); $i++) {
$c = $array[$i];
foo($c);
}
?>

I'm completely sure what it is you are asking but here would be a simple solution:
Change foo to:
function foo(){
$args = func_get_args()[0];
}
$args will then contain the array of element you pass into foo() if you called it like this:
foo($cars);
In case you may be passing more than just the array parameter you would need to loop over the arguments and then could do something with each:
foo(){
$args = func_get_args();
while(!empty($args))
{
//do something with each argument. ie. print out it's value
print_r(array_shift($args));
}
}
Call it again by the same way: foo($cars);
It seems a little bit strange what you are trying to so though as I think you could just write you foo method as:
foo($array){
foreach($array as $array_item)
{
// do something with each item ie. print out it's value
print_r($array_item);
}
}

Related

Pass-by-reference for functions with varying length of functions

I have a function with optional number of arguments, something like this:
function DoSomething()
{
$args = funct_get_args();
// and the rest of function
}
In the function above, how can I define the first argument to be passed by reference?
So when I calling it, I be able to do so:
DoSomething(&$first, $second, $third);
Simply declare it in the parameter list:
function DoSomething(&$first) {
$args = func_get_args();
// and the rest of function
}
DoSomething($first, $second, $third);

passing multiple arguments to function php

Apologies for the newbie question but i have a function that takes two parameters one is an array one is a variable function createList($array, $var) {}. I have another function which calls createList with only one parameter, the $var, doSomething($var); it does not contain a local copy of the array. How can I just pass in one parameter to a function which expects two in PHP?
attempt at solution :
function createList (array $args = array()) {
//how do i define the array without iterating through it?
$args += $array;
$args += $var;
}
If you can get your hands on PHP 5.6+, there's a new syntax for variable arguments: the ellipsis keyword.
It simply converts all the arguments to an array.
function sum(...$numbers) {
$acc = 0;
foreach ($numbers as $n) {
$acc += $n;
}
return $acc;
}
echo sum(1, 2, 3, 4);
Doc: ... in PHP 5.6+
You have a couple of options here.
First is to use optional parameters.
function myFunction($needThis, $needThisToo, $optional=null) {
/** do something cool **/
}
The other way is just to avoid naming any parameters (this method is not preferred because editors can't hint at anything and there is no documentation in the method signature).
function myFunction() {
$args = func_get_args();
/** now you can access these as $args[0], $args[1] **/
}
You can specify no parameters in your function declaration, then use PHP's func_get_arg or func_get_args to get the arguments.
function createList() {
$arg1 = func_get_arg(0);
//Do some type checking to see which argument it is.
//check if there is another argument with func_num_args.
//Do something with the second arg.
}

Store dynamic number of arguments by reference in object, to be changed later

Ok I've got a unique problem. I have a function being called, and I need this to work with how it's already being called. I've put together some code that shows as close as I can get to the answer:
class some_class {
private $_some_stuff = array();
public function some_method()
{
$args = func_get_args();
foreach($args as &$name)
{
$this->_some_stuff[] =& $name;
}
}
public function other_method()
{
for ($i = 0; $i < count($this->_some_stuff); $i++)
{
$this->_some_stuff[$i] = 'somevalue';
}
}
}
$some_object = new some_class();
$one = 'firstever';
$two = 'secondever';
$some_object->some_method(&$one, &$two);
$some_object->other_method(&$one, &$two);
echo $one;
echo '<br>...<br>';
echo $two;
I need $one and $two at the end to output 'somevalue'. If it's not clear, I need to be able to pass by reference some values into one method of an object and later have a separate method of the object still be able to access those values;
I believe that this works:
public function some_method()
{
$backtrace = debug_backtrace();
$args = $backtrace[0]['args'];
foreach($args as &$name)
{
$this->_some_stuff[] =& $name;
}
}
but as others have said, "how it's already being called" is call-time pass by reference, which is deprecated
Call-time pass-by-reference has been deprecated, because the result is a hard code.
Try to reorganize your application
You can't use func_get_args() because as the manual says it does not return by reference:
Returns an array in which each element is a copy of the corresponding member of the current user-defined function's argument list.
It appears from testing that func_get_arg() has the same behavior.
The only way to instruct PHP to provide an argument by reference to a function is with the & in the function argument list. Since you don't have an argument list, what you want is impossible.
It's also hideous! Pass-by-reference in PHP is fraught with problems and should be avoided.
However, if you are willing to change your some_method() signature, you can do the following:
class some_class {
private $_some_stuff = array();
public function some_method(&$args) // notice we accept a single arg by reference
{
foreach ($args as &$arg) {
$this->_some_stuff[] =& $arg;
}
}
public function other_method()
{
for ($i = 0; $i < count($this->_some_stuff); $i++)
{
$this->_some_stuff[$i] = 'somevalue';
}
}
}
$some_object = new some_class();
$one = 'firstever';
$two = 'secondever';
// now whenever you call this method, use this EXACT PATTERN:
$args = array(&$one, &$two); // this MUST be its own statement on its own line, and MUST have referenced elements!
$some_object->some_method($args); // CANNOT do $some_object->some_method(array(&$one, &$two)); !!!
$some_object->other_method();
var_dump($some_object);
var_dump($args);
var_dump($one);
var_dump($two);
That will do what you want.
Also note that call-time pass-by-reference (thefunc(&$foo);) is depreciated and may not work anymore.

pass variables in array as function paramaters?

I have a function that does something similar to this:
function load_class($name){
require_once('classes/'.$name.'.php');
return new $name();
}
what I want to do is modify it so I can do something like this
function load_class($name, $vars = array()){
require_once('classes/'.$name.'.php');
return new $name($array[0], $array[1]);
}
The general gist of it is.
I want to be able to pass in an array of values that, gets used as the parameters for the class.
I dont want to pass in the actual array.
is this possible?
Of course, it's called var args and you want to unpack them. http://php.net/manual/en/function.func-get-arg.php. Check out the examples... unpacking an array of arguments in php.
See Also How to pass variable number of arguments to a PHP function
if you are trying to load classes then you could use __autoload function
more information here
You can call functions this way with call_user_func_array, but in the case of a class constructor, you should use ReflectionClass::newInstanceArgs:
class MyClass {
function __construct($x, $y, $z) { }
}
$class = new ReflectionClass("MyClass");
$params = array(1, 2, 3);
// just like "$instance = new MyClass(1,2,3);"
$instance = $class->newInstanceArgs($params);
Your code might look like this:
function load_class($name, $vars = array()){
require_once('classes/'.$name.'.php');
$class = new ReflectionClass($name);
return $class->newInstanceArgs($vars);
}

Passing variable argument list to sprintf()

I would like to write a function that (amongst other things) accepts a variable number of arguments and then passes them to sprintf().
For example:
<?php
function some_func($var) {
// ...
$s = sprintf($var, ...arguments that were passed...);
// ...
}
some_func("blah %d blah", $number);
?>
How do I do this in PHP?
function some_func() {
$args = func_get_args();
$s = call_user_func_array('sprintf', $args);
}
// or
function some_func() {
$args = func_get_args();
$var = array_shift($args);
$s = vsprintf($var, $args);
}
The $args temporary variable is necessary, because func_get_args cannot be used in the arguments list of a function in PHP versions prior to 5.3.
use a combination of func_get_args and call_user_func_array
function f($var) { // at least one argument
$args = func_get_args();
$s = call_user_func_array('sprintf', $args);
}
Or better yet (and a bit safer too):
function some_func(string $fmt, ... $args) {
$s = vsprintf($fmt, $args);
}
This is PHP 7.4, not sure if it works in earlier versions.
use $numargs = func_num_args();
and func_get_arg(i) to retrieve the argument
Here is the way:
http://www.php.net/manual/en/functions.arguments.php#functions.variable-arg-list
basically, you declare your function as usual, without parameters, then you call func_num_args() to find out how many arguments they passed you, and then you get each one by calling func_get_arg() or func_get_args(). That's easy :)

Categories