Henrik Mortensen
Henrik Mortensen

Reputation: 11

Passing arrays from one function to another - one comes out empty, the other one doesn't?

I'm pretty new to OOP php, but have been coding procedural for some years now. It's a wholly different way of coding (at least to me), so I just can't wrap my head around this:

Basically, I need to extract MySQL data and display it in a table. For now, I have a class, DBQuery, with two functions - one for querying the data and storing it in an array, and one for rendering the table using the contents from the array.

If I var_dump() the array from the query class, i get contents from the database, like I should. But if I do the same in the displayTable() function, it is empty. However, I have made a $testvar array that var_dump() fine in both functions, so I might have an error in how I process the $data array, causing it to destroy itself at some point, or I'm not passing it the right way.

I've been struggling with this for 3 days now, and I'm sure I'm missing an important detail somewhere - just can't pinpoint it.

My DBQuery class:

class DBQuery extends dbc {

    private $query;
    private $testvar = array('testing one','testing two','testing three');
    private $data = array();

    public function __construct($sqlQuery) {


        $testvar = $this->testvar;
        $data = $this->data;

        $this->query = $sqlQuery;

        $result = $this->connect()->query($sqlQuery) or die('Database error');
        $numRows = $result->num_rows;
        if ($numRows > 0) {
            while ($row = $result->fetch_assoc()) {
                $data[] = $row;
            }

            var_dump($data); // ***** THIS HAS CONTENT *****

        }

    }

    public function displayTable() {

        var_dump($this->testvar); // ***** THIS HAS CONTENT *****
        var_dump($this->data);    // ***** THIS IS EMPTY *****

    }
}

And my view:

<?php
    $query = new DBQuery("SELECT * FROM users");
    $query->displayTable();
?>

What am I doing wrong here? :)

Upvotes: 1

Views: 55

Answers (1)

Sean Bright
Sean Bright

Reputation: 120714

From PHP's array documentation:

Array assignment always involves value copying.

So this line is making a copy of the array, not creating a "pointer" or "reference":

$data = $this->data;

In your __construct, change every occurrence of $data to $this->data and it will work as you intend. Alternatively you could do:

$data = &$this->data;

Which will create a reference, but will only serve to confuse the situation more.

Upvotes: 1

Related Questions