#21380 [Opn]: Ability to assign to $this in constructor of class

From: Date: Fri, 03 Jan 2003 04:26:51 +0000
Subject: #21380 [Opn]: Ability to assign to $this in constructor of class
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-28935@lists.php.net to get a copy of this message
ID: 21380 User updated by: matt-php@sprynewmedia.com Reported By: matt-php@sprynewmedia.com Status: Open Bug Type: Class/Object related Operating System: Linux (redhat) PHP Version: 4.3.0 New Comment: Certainly not a big deal but it was Jesus M. Castagnetto that asked me to report this, not Stig. Thanks. Previous Comments: ------------------------------------------------------------------------ [2003-01-02 22:20:38] matt-php@sprynewmedia.com (Stig asked me to report this.) Here's the code and the explanation will follow: -------------------------------------- class Error { var $e = ''; function Error($msg) { $this->e = $msg; } } class Foo { var $n; function &Foo($n) { if ($n < 0) { // note use of assignment operator "=" $this = new Error('Foo does not like that negative stuff'); } else { $this->n = $n; } } } $a = new Foo(-1); print_r($a); Outputs: error Object ( [e] => Foo does not like that negative stuff ) -------------------------------------- Currently, if one assignes to $this in the constructor using the assignment operator (=) the $this reference will be overwritten and so the constructor will return something other than the object requested by the new operator. This does not appear to apply to the assign by reference operator (=&) that is, it doesn't appear to be possible to overwrite the reference in $this with another reference. However, using "=" allows one to set $this to anything; it doesn't even have to be an object and that item will be returned from the new operator via the constructor. The question is, is this a feature, and if so, will it continue to be so? Or, is it a bug? If it's a feature it makes returning a PEAR error object quite simple and furthermore I have seen some PEAR code (can't remember where exactly) that uses this feature so if it is a bug that will have to be fixed too. I would like to know if this can be relied upon into the future. './configure' '--prefix=/usr/local' '--with-pspell' '--with-imap' '--with-imap-ssl' '--with-gettext' '--with-apache=/usr/local/src/apache_1.3.27' '--with-mysql=/usr' '--enable-force-cgi-redirect' '--enable-bcmath' '--enable-discard-path' '--enable-pear' '--with-kerberos' '--with-zlib' '--enable-ftp' '--with-mm' '--enable-force-cgi-redirect' Thanks, Matt Friedman. ------------------------------------------------------------------------ -- Edit this bug report at http://bugs.php.net/?id=21380&edit=1

« previous php.bugs (#28935) next »