Rodney Grump
Rodney Grump

Reputation: 3

How to setup up an array of objects using methods of a class in PHP

I am trying to create an array of objects for which I will be using chaining and I am having an issue I am hoping I can get help with. Here is the code I have:

$sql = new sql();
$sqlList[] = $sql->setTable('TableTest1');
$sqlList[] = $sql->setTable('TableTest2');
$sqlList[] = $sql->setTable('TableTest3');
$testDB->delete($sqlList);

The sql class contains a private variable called table which has setter and getter methods like this:

public function setTable($setTable)
{
    $this->table = $setTable;
    return $this;
}

public function getTable()
{
    return $this->table;
}

To test this I have a simple delete method in the $testDB object like this:

public function delete($sql ,$setClear = true)
{
    echo "<pre>";
    print_r($sql);
    echo "</pre>";
}

I am hoping to return an array with elements containing the three different TableTest values but instead all three contain just the last entry of 'TableTest3' like this:

Array
(
[0] => sql Object
    (
        [table:sql:private] => TableTest3
    )

[1] => sql Object
    (
        [table:sql:private] => TableTest3
    )

[2] => sql Object
    (
        [table:sql:private] => TableTest3
    )
)

I am using PHP 5.4.7. What am I doing wrong? A programmer with much more experience than me suggested this method to be able to make an array of different settings to step through and I am trying this to test my code. It appears to me it is putting a reference to the object $sql in each of the entries of the array instead of a copy of the actual object as I intend.

Upvotes: 0

Views: 60

Answers (2)

Passerby
Passerby

Reputation: 10070

With your setTable method looks like this:

public function setTable($setTable)
{
    $this->table = $setTable;
    return $this;
}

$sqlList[] = $sql->setTable('TableTest1');
$sqlList[] = $sql->setTable('TableTest2');
$sqlList[] = $sql->setTable('TableTest3');

All three "elements" in $sqlList are only $sql.

If you want to create a new instance upon setTable, you could try something like this:

public function setTable($setTable)
{
    $class=__CLASS__;
    $obj=new $class;
    $obj->table=$setTable;
    return $obj;
}

Upvotes: 0

Matt Runion
Matt Runion

Reputation: 1071

You only have "one" object, created when you did

$sql = new sql();

And you have just changed the private $table variable three times. you need THREE $sql objects with each set to their own table. Similar to:

$sql = new sql();
$sqlList[] = $sql->setTable('TableTest1');
$sql = new sql();
$sqlList[] = $sql->setTable('TableTest2');
$sql = new sql();
$sqlList[] = $sql->setTable('TableTest3');
$testDB->delete($sqlList);

Upvotes: 1

Related Questions