note 86023 added to language.types.object
| From: | wbcarts at juno dot com | Date: | Mon, 29 Sep 2008 22:40:14 +0000 |
| Subject: | note 86023 added to language.types.object | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-144889@lists.php.net to get a copy of this message | ||
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!
-->
----
Server IP: 69.147.83.197
Probable Submitter: 67.150.2.131
----
Manual Page -- http://www.php.net/manual/en/language.types.object.php
Edit -- https://master.php.net/note/edit/86023
Del: integrated -- https://master.php.net/note/delete/86023/integrated
Del: useless -- https://master.php.net/note/delete/86023/useless
Del: bad code -- https://master.php.net/note/delete/86023/bad+code
Del: spam -- https://master.php.net/note/delete/86023/spam
Del: non-english -- https://master.php.net/note/delete/86023/non-english
Del: in docs -- https://master.php.net/note/delete/86023/in+docs
Del: other reasons-- https://master.php.net/note/delete/86023
Reject -- https://master.php.net/note/reject/86023
Search -- https://master.php.net/manage/user-notes.php