1

Today I just discovered that in php you can do :

$instance = new MyObject();

// Here $instance->getName() == 'First Instance'
$instance->setName('First Instance');

// Here $newInstance->getName() == null
$newInstance = new $instance();

Obviously $newInstance is a valid 'MyObject' object.

Can someone tell me what this way to go involve and if it is or isn't a must NOT do?

Thx mates !

2
  • What are you trying to achieve? The last line of that code makes no sense. I would have expected it to fatal, but apparently not O_o Commented Jun 9, 2016 at 12:41
  • I am using a function which takes an object in parameter, which I don't know the class, use a function to get more details about the object then cast a new class instance sending using all the details. I create a new class because this function is part of a project where I get object details using an API and each function which get information from this API return a 'new MyObject($apiResults)' so I want to keep this way to go even for this function which is more general... Commented Jun 9, 2016 at 12:47

1 Answer 1

1

You need to use what is called a "Singleton Design Pattern" to achieve your goal, which, if I'm not wrong is that you want to use the same Object, every time an Object of the class is created.

class Singleton {
private static $instance;

public function __construct() {
        if (isset(self::$instance)) {
            $object         = __CLASS__;
            self::$instance = new $object;
            return self::$instance;
        }
    }
}

Here, the constructor checks if there is already an instance of the class, if there is, it returns that object itself. Else it creates a new one.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.