0

I'm trying to append some data to an array declared inside a class by using a function local to that class, but a dump from the outside, after the append, is reporting an empty array:

Checking...
array(0) { }

Here is the code:

error_reporting(E_ALL);
ini_set('display_errors', '1');

class workerClass {
    // With the following declaration, the dump outside the class will report only "a", "b" and "c".
    //public $arr = array("a", "b", "c");
    // With the following declaration instead, the dump outside the class will report an empty array.
    public $arr = array();

    function appendData() {
        global $arr;

        $arr[] = "d";
    }

}

// Start check.
echo "Checking...<br />";

$worker = new workerClass();
// Trying to append some data to the array inside the class.
$worker -> appendData();
var_dump($worker -> arr);
?>

What am I doing wrong?

  • The `$arr` you appended to inside the class is the global one, so `var_dump($arr)`. To use the `workerClass::$arr` property as your last line currently assumes, you would have had to assign as `$this->arr[] = 'd';` – Michael Berkowski Jun 18 '13 at 16:22
  • Welcome to Stack Overflow, Maurizio. Please give the [about page](http://stackoverflow.com/about) a read if you haven't already. –  Jun 18 '13 at 16:30

1 Answers1

1

You're assinging the value to global $arr instead of the object's $arr.

function appendData() {
    global $arr;

    $arr[] = "d";
}

should be

function appendData() {
    $this->arr[] = "d";
}

You can find similar information in PHP's documentation regarding Classes and Objects.

  • Thank you! I really need to dig deeper in PHP to get skilled about. – Maurizio Dagradi Jun 18 '13 at 16:31
  • It takes time, and there's more to it than learning the language. When it comes to Object Oriented Programming (OOP) you also have to structure your objects and methods so they're versatile, organized, and secure. It takes a long time to get good at, so you just have to keep practicing, and asking questions here of course. –  Jun 18 '13 at 16:36