Array reference in class error in php

I have this class that fills and prints an array

<?php

class testArray
{
    private $myArr;

    public function __construct() { 
        $myArr = array();
    }
    public static function PopulateArr() {

        $testA = new testArray();
        $testA->populateProtectedArr();
        return $testA;

    }
    protected function populateProtectedArr()
    {
        $this->myArr[0] = 'red'; 
        $this->myArr[1] = 'green'; 
        $this->myArr[2] = 'yellow';
        print_r ($this->myArr); 


    }
    public function printArr() {
        echo "<br> 2nd Array";
        print_r ($this->myArr);
    }
}
?>

I am instantiating this class from another file and trying to print an array in another function.

<?php
    require_once "testClass.php";


    $u = new testArray();
    $u->PopulateArr();
    $u->printArr();
?>

I can not print the array in printArr(). I want to get a reference to the array in which I set the values.

+4
source share
3 answers

You just missed one, you need to re-assign the result $u->PopulateArr();to $u, otherwise you will not get the object that you created from this method, as follows:

$u = new testArray();
$u = $u->PopulateArr(); // this will work
$u->printArr();

This can also be done as follows:

$u = testArray::PopulateArr();
$u->printArr();
+1
source

It seems like your object $unever fills a private array.

$testA .

+1

class testArray
{
    private $myArr;

    public function __construct() { 
        $this->myArr = array();
    }
    public static function PopulateArr() {

        $testA = new testArray();
        $testA->populateProtectedArr();
        return $testA;

    }
    protected function populateProtectedArr()
    {
        $this->myArr[0] = 'red'; 
        $this->myArr[1] = 'green'; 
        $this->myArr[2] = 'yellow';
        return $this->myArr;
    }
    public function printArr() {
        echo "<br> 2nd Array";
        return $this->PopulateArr();
    }
}

another.php

require_once "testClass.php";
$u = new testArray();
print_r($u->PopulateArr());
print_r($u->printArr());

Here we refer to the values protected function PopulateArrinstead of typing inside the function. I just replaced it with returnand printed it on another file, and inside the printArrfunction just called the function PopulateArrand that it

+1
source

All Articles