What effect does new(new Hoge()) have?

Asked 1 months ago, Updated 1 months ago, 3 views

While reading the code
Found source code similar to ↓.
(For private repositories, we will refrain from publishing specific source codes.)

$ins=new Hoge();
・・・・・・
$ins2 = new$ins();

What does this mean?
I've never seen it before, so I'm concerned about it.
It doesn't even appear in the search, so I don't understand the specific impact.

I look forward to hearing from you.

php

2022-09-30 11:08

1 Answers

The title new(new Hoge()) is not accurate.
Create another instance of the object from which the instance originated (for example, the Hoge object), which is also mentioned in the here.As you can see by doing the following, there is no dependency between the new instance and the original instance.This instruction can be used in PHP 5.3.0 and above.

<?php
class Hoge {
    public$val = 0;
    public function sample() {echo'sample'.nl2br(PHP_EOL);}
}

$obj1 = new Hoge();
$obj1->val=1;
$obj2 = new$obj1();
echo$obj1->val.nl2br(PHP_EOL);//1
echo$obj2->val.nl2br(PHP_EOL);//0
$obj2->sample();

var_dump($obj1!==$obj2); // True


2022-09-30 11:08

If you have any answers or tips


© 2022 OneMinuteCode. All rights reserved.