How to resolve duplicate PHP object?

Asked

Viewed 104 times

7

I have 2 objects with different values, but when I save it saved 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 registration id $obj1 but with $objet2 data.

  • What does that line mean ? $objet2 = $obj1 = new Objeto();.

  • I believe the problem lies on this line: $objet2 = $obj1 = new Objeto();. You are creating an instance for two objects. I may be wrong...

2 answers

9


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

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

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();

2

I checked, I can clone 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.