1

Given the following structure:

class B 
{
    private $_b;
    private __constructor() { }

    public function setValue( $value ) 
    {
        $this->_b->setValue( $value );
    }

    public static function load( &$__b ) 
    {
        $B = new B();
        $B->_b = $__b;
        return $B;
    }
}
class A 
{
    private $_b;

    public function getB() 
    {
        return B::load( $this->_b );
    }

    public function save() 
    {
        $this->_b->save();
    }
}
$_SESSION['a'] = new A();

The following does not work:

$b = $_SESSION['a']->getB();
$b->setValue( 'value' );
$_SESSION['a']->save();

However, the following does work:

$_SESSION['a']->getB()->setValue( 'value' );
$_SESSION['a']->save();

I know someone here will see what's wrong, or if it's not even possible.

Nahydrin
  • 13,197
  • 12
  • 59
  • 101

2 Answers2

1

What exactly are you trying to achieve here? Is your test considering the un/serialize process happening when sessions are opened / closed?

This should not ever work. A::getB() does not update its reference kept in A::_b. B::load() receives the data by reference, but does not referentially assign it to $B->_b. Assuming that $__b is an object itself, this will work in PHP5. Not because you passed it to the load() function by reference - but because objects are always handled referentially.

maybe you want to elaborate on your code example. Explaining how the the value $_SESSION['a'] came to be would be a great start.

rodneyrehm
  • 13,442
  • 1
  • 40
  • 56
  • I added how `$_SESSION['a']` is created. This did work before and the reference works because it is created using a reference. The underlying `_b` is all that needs to be a reference, the class itself does not need to be. – Nahydrin Mar 01 '12 at 18:02
  • Sorry, but `$a = new A(); $b = $a->getB(); $b->setValue("v");` will cause a Fatal Error `Called method on non-object`. – rodneyrehm Mar 01 '12 at 18:06
0

This question was not needed, the code in the original post works exactly as it is intended (pass-by-reference), and allows for storing in a variable.

My issue was with modifying the private $_b incorrectly in the constructor which was forcing it not to be a reference.

Nahydrin
  • 13,197
  • 12
  • 59
  • 101