Answer the question
In order to leave comments, you need to log in
How to save an object with a different property to a variable without changing the object?
Hello, there is a code:
class test {
public $var = 'variable';
public function setVar($param) {
$this->var = $param;
}
}
$Obj = new test();
$str = $Obj->setVar('new variable');
$Obj = new test();
$Obj2= clone $Obj;
$str = $Obj2->setVar('new variable');
Answer the question
In order to leave comments, you need to log in
Well, it will be correct through a clone
In general, a constructor will not be superfluous You can
save the standard value in a property and pull it if you wish
All properties must be private or protected
If code, that is, options for immutability
class Test
{
private $array = [];
public function __construct(array $array)
{
$this->array = $array;
}
public function immutable(): self
{
return clone $this;
}
public function limit(int $limit, int $offset = 0): self
{
return new self(array_slice($this->array, $offset, $limit));
}
}
In a particular case, you can create a new object in the method:
class test {
public $var = 'variable';
public function setVar($param) {
$self = new self();
$self->var = $param;
return $self;
}
}
$Obj = new test();
$Obj2 = $Obj->setVar('new variable');
echo $Obj->var;
echo $Obj2->var;
Think of an object as a box of data.
Created a box. I put something in there. I put a label on the box with a variable.
If you want another object - it's another box, create a new one or copy (through cloning) the old one. You can put another box in a variable.
But remember that if none of the variables contains information about your mailbox, then you have lost it.
I.e
$obj = new Obj;
$obj = new Obj;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question