note 86433 deleted from language.oop5.static by cmb

From: Date: Sun, 01 Sep 2019 07:24:29 +0000
Subject: note 86433 deleted from language.oop5.static by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-212050@lists.php.net to get a copy of this message
Note Submitter: wbcarts at juno dot com ---- [NB: This is a copy of the note by juno dot com on 11-Sep-2008 04:53, but with syntax highlighting.] A CLASS WITH MEAT ON IT'S BONES... I have yet to see an example that I can really get my chops into. So I am offering an example that I hope will satisfy most of us. <?php class RubberBall { /* * ALLOW these properties to be inherited TO extending classes - that's * why they're not private. * * DO NOT ALLOW outside code to access with 'RubberBall::$property_name' - * that's why they're not public. * * Outside code should use: * - RubberBall::getCount() * - RubberBall::setStart() * These are the only routines outside code can use - very limited indeed. * * Inside code has unlimited access by using self::$property_name. * * All RubberBall instances will share a "single copy" of these properties - that's * why they're static. */ protected static $count = 0; protected static $start = 1; protected static $colors = array('red','yellow','blue','orange', 'green', 'white'); protected static $sizes = array(4, 6, 8, 10, 12, 16); public $name; public $color; public $size; public function __construct(){ $this->name = 'RB_' . self::$start++; $this->color = (int) rand(0, 5); $this->size = self::$sizes[(int) rand(0, 5)]; self::$count++; } public static function getCount(){ return self::$count; } public static function setStart($val){ self::$start = $val; } /* * Define the sorting rules for RubberBalls - which is to sort by self::$colors. * PHP's usort() method will call this function many many times. */ public static function compare($a, $b){ if($a->color < $b->color) return -1; else if($a->color == $b->color) return 0; else return 1; } public function __toString(){ return "RubberBall[ name=$this->name, color=" . self::$colors[$this->color] . ", size=" . $this->size . "\"]"; } } # RubberBall counts the number of objects created, but allows us to # set the starting count like so: RubberBall::setStart(100); # create a PHP Array and initialize it with (12) RubberBall objects $balls = array(); for($i = 0; $i < 12; $i++) $balls[] = new RubberBall(); # sort the RubberBall objects. PHP's usort() calls RubberBall::compare() to do this. usort($balls, array("RubberBall", "compare")); # print the sorted results - uses the static RubberBall::getCount(). echo 'RubberBall count: ' . RubberBall::getCount() . '<br><br>'; foreach($balls as $ball) echo $ball . '<br>'; ?> I'm running out of room so I have not displayed the output, but it is tested and it works great.

« previous php.notes (#212050) next »