note 99453 added to language.oop5.magic

From: Date: Wed, 18 Aug 2010 15:13:44 +0000
Subject: note 99453 added to language.oop5.magic
Groups: php.notes 
Request: Send a blank email to php-notes+get-171799@lists.php.net to get a copy of this message
Thought I would just explain something about __get and __set here. Imgine you have a class like so: class user_bo{ protected $attributes = Array(); public function __get($key){ return array_key_exists($key, $this->attributes) ? $this->attributes[$key] : null; } public function __set($key, $value){ $this->attributes[$key] = $value; } /** Constructor **/ public function __construct(){} } now imagine you add a function like so to this class: public function update(){ global $database; $fields = $database->connection->getTable("users"); $set = ""; foreach($fields as $field => $info){ if(isset($this->$field)){ if($this->$field == "now()"){ $set .= $field."=".mysql_real_escape_string($this->$field).", "; }elseif($this->$field == null){ $set .= $field."=null, "; }else{ $set .= $field."='".mysql_real_escape_string($this->$field)."', "; } } } $output_set = substr($set, 0, -2); $query = "UPDATE users SET $output_set WHERE sequal_user_id = '$this->sequal_user_id'"; mysql_query($query) or sqlerrorhandler("(".mysql_errno().") ".mysql_error(), $query, $_SERVER['PHP_SELF'], __LINE__); return true; } The if(isset($this->$field)) will return false everytime. Instead of isset in loops like this you should use ($this->$field). isset returns false even when the field is populated and in theory it should never return false since in my __get: return array_key_exists($key, $this->attributes) ? $this->attributes[$key] : null; I return null if my variable don't exist. ---- Server IP: 69.147.83.197 Probable Submitter: 81.187.108.206 ---- Manual Page -- http://www.php.net/manual/en/language.oop5.magic.php Edit -- https://master.php.net/note/edit/99453 Del: integrated -- https://master.php.net/note/delete/99453/integrated Del: useless -- https://master.php.net/note/delete/99453/useless Del: bad code -- https://master.php.net/note/delete/99453/bad+code Del: spam -- https://master.php.net/note/delete/99453/spam Del: non-english -- https://master.php.net/note/delete/99453/non-english Del: in docs -- https://master.php.net/note/delete/99453/in+docs Del: other reasons-- https://master.php.net/note/delete/99453 Reject -- https://master.php.net/note/reject/99453 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#171799) next »