Search code examples
phpoopreferencepass-by-referencetraits

How can I store a variable by passing it by reference in PHP?


I am trying to grasp an OOP concept brought into PHP 7+ for Conflict Resolution. I also want to make a dynamic call to save() in my design, which will take in a argument by reference.

To test the concept before I created this addition to my framework, I wanted to try the basics of simply outputting the zval of a variable.

My current trait looks like this:

trait Singleton {
    # Holds Parent Instance
    private static  $_instance;
    # Holds Current zval
    private         $_arg;

    # No Direct Need For This Other Than Stopping Call To new Class
    private function __construct() {}

    # Singleton Design
    public static function getInstance() {
        return self::$_instance ?? (self::$_instance = new self());
    }

    # Store a reference of the variable to share the zval
    # If I set $row before I execute this method, and echo $arg
    # It holds the correct value, _arg is not saving this same value?
    public function bindArg(&$arg) { $this->_arg = $arg; }

    # Output the value of the stored reference if exists
    public function helloWorld() { echo $this->_arg ?? 'Did not exist.'; }
}

I then created a class which utilises the Singleton trait.

final class Test {
    use \Singleton { helloWorld as public peekabo; }
}

I passed in the variable I wanted to reference like so, since the method expects a reference of the variable - it does not need to be set yet.

Test::getInstance()->bindArg($row);

I now want to mimic the concept of looping through rows from a database result, the concept is to allow a save() method to be added to my design, but getting the basic concept working comes first.

foreach(['Hello', ',', ' World'] as $row)
    Test::getInstance()->peekabo();

The issue is, the output looks like this:

Did not exist.Did not exist.Did not exist.

My expected output would look like:

Hello, World

How can I store the zval inside of my class for later usage within a separate method?


Demo for future viewers of this now working thanks to the answers

Demo of this working for a database concept like I explained in the question here:

"I now want to mimic the concept of looping through rows from a database result, the concept is to allow a save() method to be added to my design"


Solution

  • Use public function bindArg(&$arg) { $this->_arg = &$arg; } It works with PHP 7.3