php - Acceptable to instantiate from an existing object?
Get the solution ↓↓↓Solution:
I've never seen this or done this. As a result, I would probably avoid it: if it is going to cause other developers to look at it and scratch their heads (just like you did), it probably isn't worth it. I can't see any reason why you would specifically have to do this, after all.
Don't Panic has pointed out that, while not explicitly documented, there is an example of doing this in the PHP documentation. Example 5 on this page.
That being said, there is no cloning going on:
class dog {
public $name='doggy';
public function speak() {
echo "bark, bark! (my name is " . $this->name . ")\n<br>";
}
public function __clone() {
print 'This is not called!';
parent::__clone();
}
}
$class = 'dog';
$puppy = new dog;
$puppy->name = 'Puppy';
$taffy = new $puppy;
if ( spl_object_hash( $taffy ) != spl_object_hash( $puppy ) )
print 'not the same object';
$taffy->speak();
If you do the above you will find that the objects are not the same and the __clone method is never called. Also, your taffy will be initialized with the name ofdoggy
, notPuppy
. It seems this is effectively shorthand for:
$class = get_class( $puppy );
$taffy = new $class;
Answer
Solution:
This is not a matter of creating a new reference to existing object. The constructor is executed, so that means, this is a new object. I've tired it:
<?php
class dog {
public $name;
public function __construct($name = '') {
$this->name = $name ?: 'doggy';
}
public function speak() {
echo "bark, bark! (my name is " . $this->name . ")\n";
}
}
$puppy = new dog;
$puppy->speak(); #bark, bark! (my name is doggy)
$taffy = new $puppy('Snuffels');
$taffy->speak(); #bark, bark! (my name is Snuffels)
$taffy->name = "Taffy";
$taffy->speak(); #bark, bark! (my name is Taffy)
$puppy->speak(); #bark, bark! (my name is doggy)
echo $puppy;
The reason IMO is, that you can already use things likenew self
ornew parent
, see http://php.net/manual/en/language.oop5.basic.php
In the class context, it is possible to create a new object by
new self
andnew parent
.
I assume, that they implement a class recognition from things afternew
. But still a good WTF :)
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: trying to access array offset on value of type bool in
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.