1

I'm writing a function in an object and need to access an array that gets constructed when the object is created. I can access normal variables inside the function using $this->var but I can't access an array in the same way using $this->array['key']. Why can't my function use arrays?

Here's the offending code:

class User
{
    public $_x;
    public $_y;
    public $_z;
    public $_array;

    public function __construct($username)
    {
        $_x = 'a';
        $_y = 'b';
        $_z = 'c';
        $_array = array( 'red' => $_x,  'blue' => $_y,  'green' => $_z,);
    }

    public function myFunction()
    {
        echo $this->_x . "<br>";
        echo $this->_y . "<br>";
        echo $this->_z . "<br>";
        echo $this->_array['red'] . "<br>";
        echo $this->_array['blue'] . "<br>";
        echo $this->_array['green'] . "<br>";
        var_dump($this->_array);
    }
}

$user = new User;
$user->myFunction();

Which displays:

a

b

c

NULL

1
  • Are you sure about that output? Commented Aug 31, 2016 at 14:16

2 Answers 2

1

You forgot $this:

public function __construct($username)
{
    $_x = 'a';  // LOCAL variable, exists only in the constructor
    $this->_x = 'a'; // class variable
    ^^^^^----you forgot this
Sign up to request clarification or add additional context in comments.

Comments

0

You have to use the $this keyword in the constructor too:

public function __construct($username)
{
    $this->_x = 'a';
    $this->_y = 'b';
    $this->_z = 'c';
    $this->_array = array( 'red' => $this->_x,  'blue' => $this->_y,  'green' => $this->_z,);
}

1 Comment

Now $_x, $_y and $z are not defined for the array definition.

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.