note 86023 deleted from language.types.object by cmb

From: Date: Fri, 15 May 2015 19:13:34 +0000
Subject: note 86023 deleted from language.types.object by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-202546@lists.php.net to get a copy of this message
Note Submitter: wbcarts at juno dot com ---- ON-THE-FLY!!! In response to Bobs note below (and Rick's somewhat): It is much better to predefine the object you want to create. This is because in all the programs you write, you will still create objects On-the-Fly anyway: $foo = 'My String Object'; // on-the-fly! $bar = 45; // on-the-fly! $obj = new stdClass(); // on-the-fly! $obj->blah = 3; // on-the-fly! So what's missing above? Real control over WHAT your program does, HOW it does it, and HOW your data is organized. Let's say your code $obj->blah = 3 was 'blah' because 3 was your last Test Score (take no offense, I've done worse!). In that case, you could use code like so: <?php class Test{ const MIN = 0, MAX = 100; // acceptable range for a test protected $person; // person taking the test protected $score; // use the word 'score' because 'blah' is meaningless public function __construct($p, $s){ $this->person = $p; $this->score = self::clamp($s); } protected static function clamp($val){ if($val < self::MIN) $val = self::MIN; if($val > self::MAX) $val = self::MAX; return $val; } public function __toString(){ return "Test [person=$this->person, score=$this->score%]"; } } $obj = new Test("John Doe", 83); // on-the-fly! echo (object)$obj; // outputs 'Test [person=John Doe, score=83%]' ?> Writing your own class definitions help maintain the "integerity" of your objects - see how the clamp() function keeps test scores between 0 and 100 percent? PHP uses similar techniques to set min and max vals on Numbers. And, classes like Test are way more useful than objects created with an empty shell, uh em, stdClass. In addition, you can see WHAT, WHERE, WHY, and HOW your program actually works... On-the-Fly! -->

« previous php.notes (#202546) next »