Since objects are passed by reference by default now, is there maybe some special case when &$obj would make sense?
Is there ever a need to use ampersand in front of an object?
3.5k views Asked by LDusan At
2
There are 2 answers
0
Nilesh Yadav
On
There are situations where you add & in front of function name, to return any value as a reference.
To call those function we need to add & in front of object.
If we add & in front of object, then it will return value as reference otherwise it will only return a copy of that variable.
class Fruit() {
protected $intOrderNum = 10;
public function &getOrderNum() {
return $this->intOrderNum;
}
}
class Fruitbox() {
public function TestFruit() {
$objFruit = new Fruit();
echo "Check fruit order num : " . $objFruit->getOrderNum(); // 10
$intOrderNumber = $objFruit->getOrderNum();
$intOrderNumber++;
echo "Check fruit order num : " . $objFruit->getOrderNum(); // 10
$intOrderNumber = &$objFruit->getOrderNum();
$intOrderNumber++;
echo "Check fruit order num : " . $objFruit->getOrderNum(); // 11
}
}
Related Questions in PHP
- How to add the dynamic new rows from my registration form in my database?
- Issue in payment form gateway
- How to create a facet for WP gridbuilder that displays both parent and child custom fields?
- Function in anonymous Laravel Blade component
- How to change woocomerce or full wordpress currency with value from USD to AUD
- General questions about creating a custom theme Moodle CMS
- How to add logging to an abstract class in php
- error 500 on IIS FastCGI but no clue despite multiple error loggings activated
- Composer installation fails and reverts ./composer.json and ./composer.lock to original content
- How to isolate PHP apps from each other on a local machine(Windows or Linux)?
- Laravel: Using belongsToMany relationship with MongoDB
- window.location.href redirects but is causing problems on the webpage
- Key provided is shorter than 256 bits, only 64 bits provided
- Laravel's whereBetween method not working with two timestamps
- Implementing UUID as primary key in Laravel intermediate table
Related Questions in OOP
- How do I apply the interface concept with the base-class in design?
- Creating multiple instances of a class with different initializing values in Flutter
- System.InvalidCastException while inheriting a class
- How to add logging to an abstract class in php
- creating cutscenes using OOP and pygame
- What effect does the `virtual` modifier have on an interface member?
- How to pass the value of a function of one class to a function of another with the @property decorator
- Creating a C++ Class Instance for every server request?
- Dart OOP programming
- Containing Object Design
- Clean architecture/OOP and optimization: how to organize for classes with same logic
- How to get 5 LEVEL hierarchy users from database using PHP and MYSQL
- TypeError: unsupported operand type(s) for /: 'property' and 'complex'
- How can I refer to this metaclass inside a metaclass without specifying its name in the code?
- Why customed "-eq" do twice in Powershell?
Related Questions in OBJECT
- How to solve compiler error: no matching function for call to 'dmhFS::dmhFS()' in my case?
- Troubleshooting object instantiation based on role in PHP app
- Best Way to Convert js object
- Find all array keys which includes 'id' as prefix and rename them as just 'id'
- Different return value
- Data structure for a console menu in Node.js with nested options that can be navigated backwards
- Invalid constant value when passing custom object as a screen parameter in flutter
- Why are some python objects necessarily unique?
- How to pass a template parameter to an object without calling its member functions?
- How to do deep copy an object without using recursion and json methods
- What should I use between object class and Hilt @Singleton class. in Android
- How can I convert an arbitrarily deep nested object to a similarly nested Map?
- Object object error when trying to save to local storage and display
- == and Equals for Tuple<object>
- Mooc.fi Java 1 -Part07_07 Recipes
Related Questions in REFERENCE
- Call by reference confusion
- Would event listeners prevent garbage collecting objects referenced in outer function scopes?
- What is correct way to copy struct instance with fields in Go?
- Filling multiple blanks among texts in a cell using values from other cells
- How are reference to objects handled in javascript when returning object and modifying them in their original functions
- Return struct containing borrowed value in rust
- Why do different delivery methods have different results when applying PHP's global keyword?
- I have about 200 cells with an equation like [=B6] can you use a MACRO (VBA) to make each cell contain $ in front of column & row characters eg [$B$6]
- strange behavior : How elements are inserted in vba arrays?
- Can someone explain to me why after this function is called a becomes 2 instead of 3 or 4?
- Copy/Paste APA-style Text References into Word as Dynamic Citations for Automatic Bibliography
- Having trouble populating an array of UUID's into their referenced type
- Any downsides to returning a reference to struct variable in Rust?
- Need documentation or API reference to create job posts on Hirist platform
- .Net App has reference but is not being recognized in class
Related Questions in PHP-INTERNALS
- in php programming where is the array data and the address being stored?
- Are PHP zvals mutable?
- Is there an opcode in PHP VM that lets you stack allocate?
- How to create a php extension function with a return type-hint plus annotation
- How do I add a new opcode to PHP?
- PHP5 zval container vs PHP7 zval container. How references & variables are stored now?
- How to call a PHP function from zend_compile.c?
- Why the macro "ZVAL_COPY_VALUE(z,v)" seems to work unexpectedly in PHP Internal?
- Where is PHP echo implemented in the source?
- PHP memory limit -1 unlinimited
- What was PHP's "o" serialization format for?
- What userland strings get automatically interned by PHP?
- What are the limits on session names in PHP?
- how to allocate & deallocate memory in php?
- How can I overwrite an internal Zend function with a PHP extension?
Popular Questions
- How do I undo the most recent local commits in Git?
- How can I remove a specific item from an array in JavaScript?
- How do I delete a Git branch locally and remotely?
- Find all files containing a specific text (string) on Linux?
- How do I revert a Git repository to a previous commit?
- How do I create an HTML button that acts like a link?
- How do I check out a remote Git branch?
- How do I force "git pull" to overwrite local files?
- How do I list all files of a directory?
- How to check whether a string contains a substring in JavaScript?
- How do I redirect to another webpage?
- How can I iterate over rows in a Pandas DataFrame?
- How do I convert a String to an int in Java?
- Does Python have a string 'contains' substring method?
- How do I check if a string contains a specific word?
Trending Questions
- UIImageView Frame Doesn't Reflect Constraints
- Is it possible to use adb commands to click on a view by finding its ID?
- How to create a new web character symbol recognizable by html/javascript?
- Why isn't my CSS3 animation smooth in Google Chrome (but very smooth on other browsers)?
- Heap Gives Page Fault
- Connect ffmpeg to Visual Studio 2008
- Both Object- and ValueAnimator jumps when Duration is set above API LvL 24
- How to avoid default initialization of objects in std::vector?
- second argument of the command line arguments in a format other than char** argv or char* argv[]
- How to improve efficiency of algorithm which generates next lexicographic permutation?
- Navigating to the another actvity app getting crash in android
- How to read the particular message format in android and store in sqlite database?
- Resetting inventory status after order is cancelled
- Efficiently compute powers of X in SSE/AVX
- Insert into an external database using ajax and php : POST 500 (Internal Server Error)
Objects use a different reference mechanism.
&$objectis more a reference of a reference. You can't really compare them both. See Objects and references:&$objectis something else than$object. I'll give you an example:I won't answer the question if it makes sense, or if there is a need. These are opinion based questions. You can definitely live without the
&reference on objects, as you could without objects at all. The existence of two mechanisms is a consequence of PHP's backward compatibility.