- Language Reference
- References Explained

Passing by Reference
Note : There is no reference sign on a function call - only on function definitions. Function definitions alone are enough to correctly pass the argument by reference.
- Variables, i.e. foo($a)
References returned from functions, i.e.: <?php function foo (& $var ) { $var ++; } function & bar () { $a = 5 ; return $a ; } foo ( bar ()); ?> See more about returning by reference .
No other expressions should be passed by reference, as the result is undefined. For example, the following examples of passing by reference are invalid: <?php function foo (& $var ) { $var ++; } function bar () // Note the missing & { $a = 5 ; return $a ; } foo ( bar ()); // Produces a notice foo ( $a = 5 ); // Expression, not variable foo ( 5 ); // Produces fatal error class Foobar { } foo (new Foobar ()) // Produces a notice as of PHP 7.0.7 // Notice: Only variables should be passed by reference ?>
User Contributed Notes 17 notes

- Stack Overflow Public questions & answers
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Talent Build your employer brand
- Advertising Reach developers & technologists worldwide
- About the company
Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
PHP - Can you assign a member function to a variable? [duplicate]
In PHP5, variables can be evaluated as functions 1 such as:
Is there any syntax for assigning object member functions to a variable such as:
- Yes, u can use call_user_function() method of php. – Mobasher Fasihy Oct 18, 2014 at 3:56
- 1 call_user_function() does not meet my requirements.. I still have to know what class and what function I am calling to use call_user_function(). I want to code $customFunc() call to be able to call any arbitrary function at runtime without prior knowledge in knowing whether it is a built-in function, a user function, a class static function, or a class object member function. – PressingOnAlways Oct 18, 2014 at 4:09
- 1 This question is NOT a duplicate of "php call class function by string name". This question is about assigning a function/method to a variable so the variable behaves like a Closure. The "php call class function by string name" is about using a variable string in place of the actual function/method name. The variable string does not behave like a Closure. – Francisco Luz Jun 19, 2019 at 6:09
2 Answers 2
There is a way, but for php 5.4 and above...
Hm.. actually it works for static too, just use the reference by name..
And for nonstatic this notation works as well. It creates a temporary instance of the class. So, this is what you need, only you need php 5.4 and above )
- Perfect! If you can find a php5.3 solution, please let me know. I may need to have some backward compatibility. – PressingOnAlways Oct 18, 2014 at 5:40
The PHP 5.4 solution above is good. If you need PHP 5.3, I don't think you can do much better than the anonymous function approach, but you could wrap that into a function that acts very similar to the PHP 5.4 method:
This should work for any number of arguments to any (publicly visible) method.
Not the answer you're looking for? Browse other questions tagged php or ask your own question .
- The Overflow Blog
- How Intuit democratizes AI development across teams through reusability sponsored post
- The nature of simulating nature: A Q&A with IBM Quantum researcher Dr. Jamie...
- Featured on Meta
- We've added a "Necessary cookies only" option to the cookie consent popup
- Launching the CI/CD and R Collectives and community editing features for...
- Staging Ground Beta 1 Recap, and Reviewers needed for Beta 2
- The [amazon] tag is being burninated
- Temporary policy: ChatGPT is banned
Hot Network Questions
- OIDC ID Token nonce as "poor mans digital signature"
- Why are trials on "Law & Order" in the New York Supreme Court?
- FAA Handbooks Copyrights
- Can the Spiritual Weapon spell be used as cover?
- How many "grounds" are there and what is the difference?
- How to prove that the supernatural or paranormal doesn't exist?
- Finite abelian groups with fewer automorphisms than a subgroup
- What's the difference between a power rail and a signal line?
- Biodiversity through radiation
- Is it possible to create a concave light?
- Why is there a voltage on my HDMI and coaxial cables?
- Calculating probabilities from d6 dice pool (Degenesis rules for botches and triggers)
- Partner is not responding when their writing is needed in European project application
- Replacing broken pins/legs on a DIP IC package
- If someone asked you to bet between an event A and an event B having happened, how would you decide?
- Follow Up: struct sockaddr storage initialization by network format-string
- So what *is* the Latin word for “chocolate”?
- Nought and Crosses (tic-tac-toe) in C++
- Lots of pick movement
- Coasting Along the Coast
- Euler: “A baby on his lap, a cat on his back — that’s how he wrote his immortal works” (origin?)
- Draw Parcly Taxel's cutie mark
- What can a lawyer do if the client wants him to be acquitted of everything despite serious evidence?
- Is it correct to use "the" before "materials used in making buildings are"?
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .
PHP: Assign a function to a variable.
This is a short guide on how to assign an anonymous function to a variable in PHP and then call it. Note that these kind of functions are sometimes referred to as lambda functions .
Let’s start off with a simple example with no parameters:
In the code above, we created a very basic anonymous PHP function and assigned it to a variable called $myAnonymousFunction . As a result, we were then able to call the function in question by referencing $myAnonymousFunction .
Anonymous function with parameters.
Now, let’s create an anonymous PHP function that takes in parameters:
As you can see, this example doesn’t differ too much from our first one. The only difference is that it takes in a parameter called $name and prints it out.
Passing one anonymous function into another.
You can also pass one anonymous function in as a parameter to another anonymous function:
In the code above, we created two functions and assigned them to PHP variables. The first function prints out a string, whereas the second one takes in a function as a parameter before calling it. Furthermore, we passed the first function into the second function.
As a result, the script above will print the words “Hi everybody” to the browser.
Crazy, right?
Oh, and by the way, I am not sorry for putting Dr. Nick’s voice in your head.

How to Pass Variables by Reference in PHP
Pass by reference, php objects, defining variables in php, related resources.
PHP variables , but not objects, by default, are passed by value. Once PHP variables are passed by value, the variable scope, defined at the function level is linked within the scope of the function. Modification of either of the variables has no impact.
Let’s see an example:
Watch a video course Learn object oriented PHP
For passing variables by reference, it is necessary to add the ampersand ( & ) symbol before the argument of the variable.
An example of such a function will look as follows: function( &$x ).
The scope of the global and function variables becomes global. The reason is that they are defined by the same reference. Hence, after changing the global variable, the variable that is inside the function also gets changed.
Here is a clear example:
As a rule, PHP variables start with the $ sign followed by the variable name.
While assigning a text value to a variable, putting quotes around the value is necessary.
In contrast to other programming languages, PHP doesn’t have a command to declare a variable. It is generated at the moment a value is first assigned to it.
In PHP, variables are containers to store data.
The PHP variables may have both short( for instance, x and y) and more descriptive names (fruitname, age, height, and so on).
- How to Generate a Random String with PHP
- How to Define Global Variable in a JavaScript Function
PHP Tutorial
Php advanced, mysql database, php examples, php reference, php variables scope.
In PHP, variables can be declared anywhere in the script.
The scope of a variable is the part of the script where the variable can be referenced/used.
PHP has three different variable scopes:

Global and Local Scope
A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function:
Variable with global scope:
A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function:
Variable with local scope:
You can have local variables with the same name in different functions, because local variables are only recognized by the function in which they are declared.
Advertisement
PHP The global Keyword
The global keyword is used to access a global variable from within a function.
To do this, use the global keyword before the variables (inside the function):
PHP also stores all global variables in an array called $GLOBALS[ index ] . The index holds the name of the variable. This array is also accessible from within functions and can be used to update global variables directly.
The example above can be rewritten like this:
PHP The static Keyword
Normally, when a function is completed/executed, all of its variables are deleted. However, sometimes we want a local variable NOT to be deleted. We need it for a further job.
To do this, use the static keyword when you first declare the variable:
Then, each time the function is called, that variable will still have the information it contained from the last time the function was called.
Note: The variable is still local to the function.
PHP Exercises
Test yourself with exercises.
Create a variable named txt and assign the value "Hello" .

COLOR PICKER

Get your certification today!

Get certified by completing a course today!

Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your Suggestion:
Thank you for helping us.
Your message has been sent to W3Schools.
Top Tutorials
Top references, top examples, web certificates, get certified.
- Coding Ground
- Corporate Training
- Trending Categories

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
PHP Variable functions
Introduction.
If name of a variable has parentheses (with or without parameters in it) in front of it, PHP parser tries to find a function whose name corresponds to value of the variable and executes it. Such a function is called variable function. This feature is useful in implementing callbacks, function tables etc.
Variable functions can not be built eith language constructs such as include, require, echo etc. One can find a workaround though, using function wrappers.
Variable function example
In following example, value of a variable matches with function of name. The function is thus called by putting parentheses in front of variable
Live Demo
This will produce following result. −
Here is another example of variable function with arguments
In following example, name of function to called is input by user
Variable method example
Concept of variable function can be extended to method in a class
A static method can be also called by variable method technique
This will now throw exception as follows −

0 Followers
- Related Articles
- PHP Anonymous functions
- PHP Variable Basics
- PHP Variable Scope
- PHP variable Variables
- PHP User-defined functions
- Uniform variable syntax in PHP 7
- PHP How to cast variable to array?
- How to declare a global variable in PHP?
- How to assign a PHP variable to JavaScript?
- What do we mean by hash functions in PHP?
- Explain include(),require(),include_once() and require_once() functions in PHP.
- PHP Casting Variable as Object type in foreach Loop
- Convert PHP variable “11:00 AM” to MySQL time format?
- Which is faster? Constants, Variables or Variable Arrays in PHP?
- Add PHP variable inside echo statement as href link address?


IMAGES
VIDEO
COMMENTS
PHP supports passing arguments by value (the default), passing by reference, and default argument values. Variable-length argument lists and Named Arguments are also supported. Example #1 Passing arrays to functions <?php function takes_array($input) { echo "$input[0] + $input[1] = ", $input[0]+$input[1]; } ?>
You can pass a variable by reference to a function so the function can modify the variable. The syntax is as follows: <?php function foo(&$var) { $var++; } $a=5; foo($a); // $a is 6 here ?> Note: There is no reference sign on a function call - only on function definitions.
In PHP5, variables can be evaluated as functions 1 such as: function myFunc () { echo "whatever"; } $callableFunction = 'myFunc'; $callableFunction (); // executes myFunc () Is there any syntax for assigning object member functions to a variable such as:
PHP: Assign a function to a variable. This is a short guide on how to assign an anonymous function to a variable in PHP and then call it. Note that these kind of functions are sometimes referred to as lambda functions. Let’s start off with a simple example with no parameters:
PHP automatically associates a data type to the variable, depending on its value. Since the data types are not set in a strict sense, you can do things like adding a string to an integer without causing an error. In PHP 7, type declarations were added.
As a rule, PHP variables start with the $ sign followed by the variable name. While assigning a text value to a variable, putting quotes around the value is necessary. In contrast to other programming languages, PHP doesn’t have a command to declare a variable. It is generated at the moment a value is first assigned to it.
In PHP, variables can be declared anywhere in the script. The scope of a variable is the part of the script where the variable can be referenced/used. PHP has three different variable scopes: local. global.
PHP Server Side Programming Programming Introduction If name of a variable has parentheses (with or without parameters in it) in front of it, PHP parser tries to find a function whose name corresponds to value of the variable and executes it. Such a function is called variable function.