PHP: Use result of anonymous function directly as string? [duplicate] - php

This question already has answers here:
How do I immediately execute an anonymous function in PHP?
(9 answers)
Closed 10 years ago.
Is it possible to do something like this. Lets say we have a function that accepts string as argument. But to provide this string we have to do some processing of data. So I decided to use closures, much like in JS:
function i_accept_str($str) {
// do something with str
}
$someOutsideScopeVar = array(1,2,3);
i_accept_str((function() {
// do stuff with the $someOutsideScopeVar
$result = implode(',', $someOutsideScopeVar); // this is silly example
return $result;
})());
The idea is to when calling i_accept_str() to be able to directly supply it string result... I probably can do it with call_user_func which is known to be ineffective but are there alternatives?
Both PHP 5.3 and PHP 5.4 solutions are accepted (the above wanted behavior is tested and does not work on PHP 5.3, might work on PHP 5.4 though...).

In PHP (>=5.3.0, tested with 5.4.6) you have to use call_user_func and import Variables from the outer Scope with use.
<?php
function i_accept_str($str) {
// do something with str
echo $str;
}
$someOutsideScopeVar = array(1,2,3);
i_accept_str(call_user_func(function() use ($someOutsideScopeVar) {
// do stuff with the $someOutsideScopeVar
$result = implode(',', $someOutsideScopeVar); // this is silly example
return $result;
}));

Related

Can we call an anonymous function without storing it in a variable in PHP?

In Javascript, it's easy to call a function returned by another function in one single statement. Consider for example:
function createOperation(operator)
{
return Function("a", "b", "return a " + operator + "b;")
}
var result = createOperation("*")(2, 3);
Here, we call a function to create another function that multiplies two values, then call this new function with two arguments.
If I try to replicate a similar code snippet in PHP, I end up using two statements and one extra variable:
function createOperation(operator)
{
return create_function('$a,$b', 'return $a '.$operator.' $b;');
}
$temp_var = createOperation("+");
$result = $temp_var(2, 3);
The short, Javascript-like form doesn't work:
$result = createOperation("+")(2, 3);
This is especially tedious when writing an invocation chain (pseudocode):
foo(arg1)(arg2, arg3)()(...)
Which would become:
$temp1 = foo($arg1);
$temp2 = $temp1($arg2, $arg3);
$temp3 = $temp2();
...
So my question is: is there a way in PHP to call a function returned by another function without using temporary variables, or at least in one single same statement?
As seen in php repo, #NikiC is actively working on implementing his RFC, the ()() syntax is already in the trunk:
https://github.com/php/php-src/commit/64e4c9eff16b082f87e94fc02ec620b85124197d
I don't know what the release map looks like, hope we'll get decent syntax in php very soon.

php single function with multiple names / aliases [duplicate]

This question already has answers here:
How to alias a function in PHP?
(15 answers)
Closed 8 years ago.
This isn't really important but the question is more one of curiosity.
Is it possible to alias a function or define two names for it.
I know this works:
function real($p1=array(), $p2=null, $p3='default'){
return 'something';
}
function aliasForReal($p1=array(), $p2=null, $p3='default'){
return real($p1, $p2, $p3);
}
Is there a less verbose way to alias another function?
something like
function (real||aliasForReal)(...){
or
function aliasForReal extends real;
There are a couple of places I need to do this and the working method above just feels a bit dirty to me.
For instance:
using names like (begin and start) interchangeably for one function and (end and stop) for another.
function real($p1=array(), $p2=null, $p3='default'){
return 'something';
}
$real1 = 'real';
$real2 = 'real';
// etc
You can call $real1(...)
function real(){
return "real";
}
function realAlias(){
return "realAlias";
}
$p = "real";
print $p();
$p = "realAlias";
print $p();
does it help?

How to create a new object using a class-name stored in a variable? [duplicate]

This question already has answers here:
Dynamically create PHP object based on string
(5 answers)
Closed 8 years ago.
I have a bunch of functions depending on a variable, I want to be able to do something like this:
(It returns an error hence the problem I'm unable to solve)
function($x) {
fetch.$x.() // if x=Name I would like it to execute fetchName()...and so on
}
and something like this
function($x) {
$article = new \Cc\WebBundle\Entity\$X();
// if x='name' to be executed Cc\WebBundle\Entity\name()
}
Sure, you could do that:
$basename = "fetch";
$key = ...; // your logic for generating the rest of function's name
$functionName = $basename . $key;
$functionName(); // execute function
Now, the tricky part would be if functions contain arbitrary set of arguments. In that case you should use call_user_func_array (docs).
As for creating of objects, meagar explained here please clear how to achieve that.
P.S. This, in fact, has very little to do with Symfony2. This is a pure PHP question ;)
Personally, I use the handy call_user_func_array() function like this:
<?php
$class = 'MyClassName';
$method = 'someMethod';
$parameters = array('foo', 'bar', 'baz');
call_user_func_array(array($class, $method), $parameters);
I imagine you would need to escape back-slashes in any name-spaced class names though, i.e. MCB\\MyClassName.

is there an equalant to PHP array_key_exists in javascript or jquery [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Checking if an associative array key exists in Javascript
I have a PHP code block . For a purpose I am converting this to a JavaScript block.
I have PHP
if(array_key_exists($val['preferenceIDTmp'], $selected_pref_array[1]))
now I want to do this in jQuery. Is there any built in function to do this?
Note that objects (with named properties) and associative arrays are the same thing in javascript.
You can use hasOwnProperty to check if an object contains a given property:
o = new Object();
o.prop = 'exists'; // or o['prop'] = 'exists', this is equivalent
function changeO() {
o.newprop = o.prop;
delete o.prop;
}
o.hasOwnProperty('prop'); //returns true
changeO();
o.hasOwnProperty('prop'); //returns false
Alternatively, you can use:
if (prop in object)
The subtle difference is that the latter checks the prototype chain.
In Javascript....
if(nameofarray['preferenceIDTmp'] != undefined) {
// It exists
} else {
// Does not exist
}
http://phpjs.org/functions/array_key_exists:323
This is a great site for PHP programmers moving to js.

Two different return types in PHP function [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Multiple returns from function
Is it possible to return 2 results in the same PHP function? One is an array, the other is an integer. Could someone give me an example?
function functest() {
return array(1, "two");
}
list($first,$second) = functest();
There's nothing stopping you from returning whatever type you like from a function. You can return a dictionary with multiple keys, or an array of mixed object types, or whatever. Anything you like.
$arr = array();
$arr[] = $some_object;
$arr[] = 3;
$arr["a_string"] = "foo";
return $arr;
You have several options to simulate multiple return values (the first two, however, are just a kind of wrapping of multiple values into one):
Return an array with the two values: return array($myInt, $myArr); (see e.g. parse_url().)
Create a dedicated wrapper object and return this: return new MyIntAndArrayWrapper($myInt, $myArr);
Add an "output argument" to the function signature: function myFunc(&$myIntRetVal) { ... return $myArr; } (see e.g. preg_match(..., &$matches).)
What about this?
function myfunction() {
//Calculate first result
$arrayresult=...
//Calculate second result
$intresult=...
//Move in with each other . don't be shy!
return array($arrayresult,$intresult)
}
and in the other code
$tmp=myfunction();
$arrayresult=$tmp[0];
$intresult=$tmp[1];
It's totally possible since PHP doesn't use strong typing. Just return the value you want in whatever type you want. A simple example:
function dual($type) {
if ($type === 'integer')
return 4711;
else
return 'foo';
}
You can use several functions on the caller side to see which type you got, for example: gettype, is_int, is_a.

Categories