note 128434 added to language.oop5.decon
| From: | biziclop at main dot php dot net | Date: | Wed, 26 Apr 2023 15:31:20 +0000 |
| Subject: | note 128434 added to language.oop5.decon | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-220389@lists.php.net to get a copy of this message | ||
In JavaScript, you can return a different object from a constructor if necessary:
<?php // JavaScript:
function C( data ){
if( data instanceof C ) return data;
this.fruit = data;
}
var a = new C('pear');
var b = new C( a );
console.log( a === b ); // true
?>
In PHP, you can't do this, the returned value is ignored:
<?php
class C {
var $fruit;
function __construct( $data ){
if( $data instanceof self ) return $data;
$this->fruit = $data;
}
}
$a = new C('pear');
$b = new C( $a );
var_dump( $a === $b ); // bool(false)
?>
If you need the JavaScript behaviour, you can use a static method instead:
<?php
class D {
var $fruit;
function __construct( $data ){
$this->fruit = $data;
}
static function create( $data ){
if( $data instanceof self ) return $data;
return new self( $data );
}
}
$c = new D('pear');
$d = D::create( $c );
var_dump( $c === $d ); // bool(true)
?>
----
Server IP: 45.112.84.4
Probable Submitter: 80.90.13.130 (proxied: 188.143.59.161)
----
Manual Page -- https://php.net/manual/en/language.oop5.decon.php
Edit -- https://main.php.net/note/edit/128434
Del: integrated -- https://main.php.net/note/delete/128434/integrated
Del: useless -- https://main.php.net/note/delete/128434/useless
Del: bad code -- https://main.php.net/note/delete/128434/bad+code
Del: spam -- https://main.php.net/note/delete/128434/spam
Del: non-english -- https://main.php.net/note/delete/128434/non-english
Del: in docs -- https://main.php.net/note/delete/128434/in+docs
Del: other reasons-- https://main.php.net/note/delete/128434
Reject -- https://main.php.net/note/reject/128434
Search -- https://main.php.net/manage/user-notes.php