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
}
Related
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
This question already has answers here:
PHP take string and check if that string exists as a variable
(3 answers)
Closed 8 years ago.
I have a field that depends has custom text if a certain condition is met...and if it isn't the field is blank.
I have written a custom function test if a variable is set
function AmISet($fieldName) {
if (isset($fieldName)) {
echo "I am set";
}else{
echo "I am not set";
}
};
but when I attach it the field I get an error that the variable is undefined. But when I do a regular isset($fieldName);
I don't have a problem. Is there any way to get around this and have my function do this instead of the isset()?
I want to add other logic in the function but I only want it to work if the variable is set...but I don't want the undefined error if it is not.
I am new to php and really appreciate any help or direction you can give me.
Thank you for the help!
You need to pass the variable by reference:
function AmISet(&$fieldName) {
if (isset($fieldName)) {
echo "I am set\n";
} else {
echo "I am not set\n";
}
}
Test cases:
$fieldName = 'foo';
AmISet($fieldName); // I am set
unset($fieldName);
AmISet($fieldName); // I am not set
However, this function is not useful as it is, because it will only output a string. You can create a function that accepts a variable and return if it exists (from this post):
function issetor(&$var, $default = false) {
return isset($var) ? $var : $default;
}
Now it can be used like so:
echo issetor($fieldName); // If $fieldName exists, it will be printed
the $fieldName comes from a query that is performed when a checkbox
is checked. If the box is checked the query is made and the variable
is set from the query, if not it doesn't exist and the field is blank.
Filter functions are designed for this kind of tasks:
<input type="foo" value="1">
$foo = filter_input(INPUT_POST, 'foo')==='1';
(There's also a specific FILTER_VALIDATE_BOOLEAN filter you can pass as second argument.)
And now you have a pure PHP boolean that always exists.
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:
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