2

I need to change an array from outside the class, which is a class variable. For example see my code below:

<?php
class ArrayRet
{
    private $_ar = array();

    public function __construct()
    {
        $this->_ar['test1'] = 'hello1';
        $this->_ar['test2'] = 'hello2';
    }

    public function getAr()
    {
        return $this->_ar;
    }

    public function dump()
    {
        var_dump($this->_ar);
    }
}

$arRet = new ArrayRet();
$arRet->dump();
$ar = $arRet->getAr();
$ar['test2'] = 'works!!!';
$arRet->dump();
?>

$this->_ar['test2'] should be works!!! but it´s still hello2

How can I get this working?

Edit: With changing the syntax a bit as found here, it works. So, we need to change the method to this:

public function &getAr()
{
   return $this->_ar;
}

And also the call to this:

$ar = &$arRet->getAr();

2 Answers 2

2

you made 2 mistake : 1- you put your array in $ar and you changed it, so you changed $ar,Not $arRet, so your object Not changed. 2- you set _ar as private,so you can't change it directly, so you must make another function to change it. some thing like :

    <?php
    class ArrayRet
    {
        private $_ar = array();

        public function __construct()
        {
            $this->_ar['test1'] = 'hello1';
            $this->_ar['test2'] = 'hello2';
        }

        public function getAr()
        {
            return $this->_ar;
        }
        public function dump()
        {
            var_dump($this->_ar);
        }
        public function change_var($key,$val)
        {
           $this->_ar[$key] = $val;
        }
    }

    $arRet = new ArrayRet();
    $arRet->dump();
    $arRet->change_var('test1','works!!!');
    $ar = $arRet->getAr();

    $arRet->dump();
var_dump($ar);
    ?>

as you see $arRet changed and you put it into $ar.

Sign up to request clarification or add additional context in comments.

1 Comment

as far as I know, if I return a class variable, I give a reference back to the caller. But PHP copies it. And return &$this->_ar; gives me a syntax error.
1

With your current code you can't as you have declared the visibility of ArrayRet::$_ar to be private meaning it cannot be accessed outside the scope of the class.

By declaring ArrayRet::$_ar as public you can do the following...

class ArrayRet
{
    public $_ar = array();
    // ...
}

$arRet = new ArrayRet();
$arRet->_ar['test2'] = 'works!!!';
$arRet->dump();

I don't recommend directly modifying object properties from outside of the class as this can cause headaches.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.