This question already has answers here:
Anonymous recursive PHP functions
(6 answers)
Closed 1 year ago.
EDIT: I'm sorry for the duplicate, but searching for the title of this question wasn't showing such duplicate in the search result, so I was not aware there is question, already.
This won't work, because $greet is unknown by the time it will be called.
<?php
$greet = function($name)
{
printf("Hello %s\r\n", $name);
if($name != 'PHP')
{
$greet('PHP'); // $greet not defined
}
};
$greet('World');
?>
The idea is to have a recursive function that is purely in its parent scope (i.e. function in function), without the requirement to build a class.
So, how to build an anonymous recursive function in PHP, properly? Is it even possible? If so, how?
Yes you can. You need to use the $greet variable by reference, like this:
$greet = function($name) use (&$greet)
{
printf("Hello %s\r\n", $name);
if($name != 'PHP')
{
$greet('PHP');
}
};
$greet('World');
Working example:
https://3v4l.org/vUhIW
This article describes this a bit more:
https://fragdev.com/blog/php-recursion-with-anonymous-functions
Related
This question already has answers here:
PHP function overloading
(9 answers)
Closed 8 years ago.
I’m new in PHP, and I want to do the same as the follow java source-code in PHP. Can anyone help me?
someMethod(int i) {
System.out.println("message");
// more code
}
someMethod(String s) {
System.out.println("another message");
// more different code
}
You cannot overload PHP functions, as their signatures only include their name and not their argument lists: https://stackoverflow.com/a/4697712/386869
You can either do two separate functions (which I recommend) for what you're trying to do, or perhaps write one function and perform a different action for each type.
Writing two methods is straightforward:
function myFunctionForInt($param)
{
//do stuff with int
}
function myFunctionForString($param)
{
//do stuff with string
}
If you'd like to instead do it with one function and check the type (not really recommended):
function myFunction($param)
{
if(gettype($param) == "integer")
{
//do something with integer
}
if(gettype($param) == "string")
{
//do something with string
}
}
Docs for gettype()
I don't know that it's the best way. Also, for your particular example, Imat's example makes the most sense since you're just printing a message.
Okay, so you want to create a function that prints a message.
function my_function_name()
{
echo "your message here;
}
If you want a function with parameters, you can do this.
function my_function_name($params)
{
echo "your message here";
echo $params; //call the paramereters
}
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?
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.
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;
}));
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Can't use method return value in write context
I sometimes encountered this error Can't use method return value in write context. However, I don't know what does WRITE CONTEXT means in this sentence. Could someone tell me a little general explaination of it.
Thank you.
The code for this error if you want to refer to is on line if(empty($this->loadUser())) However just to clarify, I just want to find out the meaning of "write context":
public function verify()
{
if(empty($this->loadUser()))
$this->addError('username','Incorrect username.');
else
{
$user = $this->loadUser();
$project = $this->loadProject($pid);
$project->associateUserToProject($this->loadUser());
$project->associateUserToRole($this->role, $this->user->id)
}
}
public function loadUser() {
return User::model()->findByAttributes(array('username'=>$this->username));
}
empty () is not a function really.
It is a construct or macros, if you please.
It means you cannot pass an object to it as argument.
Just pure variables.
$is_use = $this->loadUser();
if (empty ($is_use))
{
...
}
empty only takes variables as an arg. empty() only checks variables as anything else will result in a parse error.
http://php.net/manual/en/function.empty.php