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?
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 use return inside a recursive function in PHP
(4 answers)
Closed 9 months ago.
I have this recursive function that calls itself until the number reaches total. I have made this demo to show the working, actually the secondFunc() conatins database queries. I'm saving values in array that is passed to secondFunc() from firstFunc(). The problem is when i call first function it shows only 1 value i.e. 1. When i uncomment the var_dump in second func it shows all the values. I know i'm doing something wrong. Please point out my mistake .What is the problem here?
function firstFunc($total){
$array=array();
$num=0;
return secondFunc($total,$num,$array);
}
function secondFunc($total,$num,$array){
$num++;
$array[$num]=$num;
if($num<$total){
secondFunc($total,$num,$array);
}
//var_dump($array);
//exit();
return $array;
}
var_dump(firstFunc(5));
Demo http://codepad.viper-7.com/Bic8ce
When you call a function recursively you must make sure to propagate the recursive call's return value back to the original caller:
if($num<$total) {
return secondFunc($total,$num,$array); // return added
}
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 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.