Object Nuking via $this re-assignment
| From: | Rob Hudson | Date: | Thu, 02 Nov 2000 21:15:54 +0000 |
| Subject: | Object Nuking via $this re-assignment | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-23461@lists.php.net to get a copy of this message | ||
Just an observation:
I recently stumbled upon this interesting (to me anyways) piece of
information while writing a class in PHP that accesses a MySQL
database.
I made a class and a few methods similar to the following:
class myClass {
var $field1, $field2;
function myClass ($id) {
$result = mysql_query ("SELECT field1, field2 FROM table WHERE id=$id");
$this = mysql_fetch_object ($result);
}
function myMethod() {
echo "Field 1: $this->field1";
}
}
My intent was to assign the result from the query of field1 and
field2 to $this->field1 and $this->field2, thereby making a shortcut
of my previous ways of returning the result to $obj and assigning
each variable by $this->field1 = $obj->field1.
I've since changed my ways and created a var $db, and assign to it
the result from a mysql_fetch_array($result) call.
After figuring out why I was getting fatal errors b/c my methods
weren't accessible, I was curious why PHP would allow me to do such
a thing. Outside of the class, object reassignment makes sense, but
I would at least expect a warning when trying to remap $this from
within the object itself.
-Rob.