A
A
Andrey Raboy2019-08-23 02:02:52
PHP
Andrey Raboy, 2019-08-23 02:02:52

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

I'm dumb about something, how to save an object with a changed property to the $str variable without affecting the original?
Of course, you can do this:
$Obj = new test();
$Obj2= clone $Obj;
$str = $Obj2->setVar('new variable');

But, this is not possible)) Do something in the method itself? Tried to make a static method, but...
Do not pay attention to the constructor and access modifiers.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dmitry, 2019-08-23
@Compolomus

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

Then work through the method, or make methods that return a new object

R
Ramzesh Halifionakis, 2019-08-23
@ramiloremispum

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;

G
Grigory Vasilkov, 2019-08-24
@gzhegow

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;

Created a box twice and assigned it to the same place - as a result, you lost the first one, no one else refers to it and it will be deleted. The same with the line will be if two lines are put into one variable, then the first one will be deleted.
Create a second one. And there play with the second box

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question