php use array as array_map first argument - php

I can't kind of make out the first return statement, can anybody help to explain how it works?
the array_map accept a function for the first arg, but here is an array. and how does array(&$this, '_trimData') work? thanks for explaining.
private function _trimData($mParam)
{
if (is_array($mParam))
{
return array_map(array(&$this, '_trimData'), $mParam);
}
$mParam = trim($mParam);
return $mParam;
}

This is a recursive function. _trimData calls itself if the parameter passed to it was an array.
array(&$this, '_trimData') is a callback to the current object's method _trimData.
The entire method could really be replaced with:
private function _trimData($mParam)
{
array_walk_recursive($mParam, 'trim');
return $mParam;
}

It is callback: $this->_trimData() (_trimData of object $this)

A bit further of an explanation about how array(&$this, '_trimData') acts as a callback, despite looking like an array:
A PHP function is passed by its name as a string... A method of an instantiated object is passed as an array containing an object at index 0 and the method name at index 1. PHP: Callbacks/Callables
So in this case, the object is &$this and the method is _trimData, and making it into an array is one way PHP allows you to pass it as a callback into array_map.

Related

How to receive specific interface's array in PHP class method?

I want to receive array of MyInterface as the in the below code.
public function saveMultiple(
\Path\To\MyInterface $attachLinks[]
);
The above code doesn't work.
So please don't tell me that just remove \Path\To\MyInterface and to use a variable $attachLinks. I'm already aware of that but this is something which I require.
There are no generic types in php, so you can not specify type «array of something».
But you may do a trick. Check types of elements in array.
array_walk($attachLinks, function (\Path\To\MyInterface $item) {});
If you wrap it in assert, you will be able to disable this check.
assert('array_walk($attachLinks, function (\Path\To\MyInterface $item) {})');
So far this is what can be done using PHP7. Till date passing arrays with specific type is not possible.
public function saveMultiple(
array $attachLinks
);
It'll now at least make sure that the method only gets array as parameter.
Maybe you can use some type of setter like:
private $attachLinks = [];
public function setter(MyInterface $var)
{
$this->attachLinks[] = $var;
}
And than use a $this->attachLinks in your function
public function saveMultiple() {
print_r($this->attachLinks);
}

Add Arguments to Existing PHP Function from Array

I'm looking to figure out how to add more arguments to a function call based on an Array and can't figure out what I need to do. The function in question doesn't work with simply passing an array, but the array has to explode somehow as if each array element was a new argument in the function call. I don't think call_user_func_array works but perhaps I don't know how to execute it properly. To give some context, the array of arguments are coming from a varying amount of $_GET arguments which is processed by an API class file I have no control over, but it appears that I can add a lot of arguments that allow the results to filter.
$arrayofarguments = array("dynamicarg1","dynamicarg2","dynamicarg3");
$runthis = example($staticargument1,
$staticargument2,
$staticargument3,
$arrayofarguments,
$staticargument4);
//run the results
echo $runthis;
Expected result
$runthis = example($staticargument1,
$staticargument2,
$staticargument3,
"dynamicarg1",
"dynamicarg2",
"dynamicarg3",
$staticargument4);
Thanks for the help! :)
I think you have to do something like
function example("blaa","foo","bar",$arrayofarguments,"test") {
$args = func_get_args();
// $arg[3] would be $arrayofarguments
foreach ( $arg[3] as $function) {
$function(); // this calls the function
}
}

PHP: How to traverse an associative-array by having a child's reference?

I have a function declaration like this:
function func(&$array){//do something};
Then I have an array like this:
$people[gender][singlePerson][property]=>value
I call my function this way:
func($people[man][person1]);
In my function now I have the parameter $array that contain the reference to:
$people[man][person1]
Now the problem...
How can i traverse the reference to get the position
$people[man]
In other word, having the reference $people[man][person1] how con i "level up" on the array?
If you pass $people['men']['person1'] to your function, there's no way how this function can know that this array has been nested within $people['men'] outside of it.
how can i "level up" on the array?
You can't. And what's more: You shouldn't need to.
The only reasonable answer here is: change the design of code to meet your requirements, try different approach, consider passing additional parameters to this function etc.
Alt aproach
What you need is a class instead of just a functoin; consither this as the call:
(new my_class($people))->func($people[man][person1]);
You will be passing the full array to your instance of my_class so you can store that in a variable or pass it as reference.
Your class the, should look like this:
class my_class {
private $my_people;
public function __construct($outside_people) {
$this->my_people = $outside_people;
}
public function func($person){
.....
}
}
Now you can access $this->my_people from the inside of your function.
Another alt aproach
Just pass the array in a seccond var. You will need to pass it by reference:
func($person, &$full_array){
....
}
Then call your function like this:
func($people[man][person1], $people);
Since $full_array is a reference to $people outside of the function you are able to modify the original array from the insides of your function.

php, I cant pass an array as reference

this is the function:
public function func(&$parameters = array())
{
}
now I need to do this:
$x->func (get_defined_vars());
but that fails. Another way:
$x->func (&get_defined_vars());
it drops an error: Can't use function return value in write context in ...
Then how to do it?
get_defined_vars() returns an array, not a variable. As you can only pass variables by reference you need to write:
$definedVars = get_defined_vars();
func($definedVars);
Though I don't really see a reason to pass the array by reference here. (If you are doing this for performance, don't do it, as it won't help.)
public function func(&$parameters = array())
{
}
Not defined correctly.
Try this way:-
call_user_func_array( 'func', $parameters );
See the notes on the call_user_func_array() function documentation for more information.

Passing an Array as Arguments, not an Array, in PHP

I seem to remember that in PHP there is a way to pass an array as a list of arguments for a function, dereferencing the array into the standard func($arg1, $arg2) manner. But now I'm lost on how to do it. I recall the manner of passing by reference, how to "glob" incoming parameters ... but not how to de-list the array into a list of arguments.
It may be as simple as func(&$myArgs), but I'm pretty sure that isn't it. But, sadly, the php.net manual hasn't divulged anything so far. Not that I've had to use this particular feature for the last year or so.
http://www.php.net/manual/en/function.call-user-func-array.php
call_user_func_array('func',$myArgs);
As has been mentioned, as of PHP 5.6+ you can (should!) use the ... token (aka "splat operator", part of the variadic functions functionality) to easily call a function with an array of arguments:
<?php
function variadic($arg1, $arg2)
{
// Do stuff
echo $arg1.' '.$arg2;
}
$array = ['Hello', 'World'];
// 'Splat' the $array in the function call
variadic(...$array);
// 'Hello World'
Note: array items are mapped to arguments by their position in the array, not their keys.
As per CarlosCarucce's comment, this form of argument unpacking is the fastest method by far in all cases. In some comparisons, it's over 5x faster than call_user_func_array.
Aside
Because I think this is really useful (though not directly related to the question): you can type-hint the splat operator parameter in your function definition to make sure all of the passed values match a specific type.
(Just remember that doing this it MUST be the last parameter you define and that it bundles all parameters passed to the function into the array.)
This is great for making sure an array contains items of a specific type:
<?php
// Define the function...
function variadic($var, SomeClass ...$items)
{
// $items will be an array of objects of type `SomeClass`
}
// Then you can call...
variadic('Hello', new SomeClass, new SomeClass);
// or even splat both ways
$items = [
new SomeClass,
new SomeClass,
];
variadic('Hello', ...$items);
Also note that if you want to apply an instance method to an array, you need to pass the function as:
call_user_func_array(array($instance, "MethodName"), $myArgs);
For sake of completeness, as of PHP 5.1 this works, too:
<?php
function title($title, $name) {
return sprintf("%s. %s\r\n", $title, $name);
}
$function = new ReflectionFunction('title');
$myArray = array('Dr', 'Phil');
echo $function->invokeArgs($myArray); // prints "Dr. Phil"
?>
See: http://php.net/reflectionfunction.invokeargs
For methods you use ReflectionMethod::invokeArgs instead and pass the object as first parameter.

Categories