How to solve duplicate PHP object?

7

I have 2 objects with different values, but when I save it it saves as a single object.

Example of how I'm using:

class Objeto {
    private $Nome;

    public function setNome($Nome){
        $this->Nome = $Nome;
    }

    public function getNome(){
        return $this->Nome;
    }
}

$objet2 = $obj1 = new Objeto();
$obj1->setNome("Pedro");
$objet2->setNome("Marcos");


salvar($obj1);
salvar($objet2);

It saves as the registry id $ obj1 but with the $ objet2 data.

    
asked by anonymous 09.09.2015 / 16:41

2 answers

9

When you use $objet2 = $obj1 = new Objeto(); , the two variables are pointing to the same object.

You can give echo in the attribute Nome of each object and see that it will always return "Frames".

Example:

class Objeto {
    private $Nome;

    public function setNome($Nome){
        $this->Nome = $Nome;
    }

    public function getNome(){
        return $this->Nome;
    }
}

$objet2 = $obj1 = new Objeto();
$obj1->setNome("Pedro");
$objet2->setNome("Marcos");

echo $obj1->getNome(); //Retorna Marcos
echo '<br />';
echo $objet2->getNome(); //Retorna Marcos

Edit:

The solution to your problem is simple, just create an object for each variable:

$obj1 = new Objetio();
$objet2 = new Objetio();
    
09.09.2015 / 16:49
2

I checked, I can make a clone of my object, so this new object gets a new reference in memory.

class Objeto {
    private $Nome;

    public function setNome($Nome){
        $this->Nome = $Nome;
    }

    public function getNome(){
        return $this->Nome;
    }
}

$obj1 = new Objeto();
$objet2 = clone $obj1; // Clonando o objeto
$obj1->setNome("Pedro");
$objet2->setNome("Marcos");

echo $obj1->getNome(); //Retorna Marcos
echo '<br />';
echo $objet2->getNome(); //Retorna Marcos
    
09.09.2015 / 22:25