7.Objects

1. Creating an Object
class Item { // a very minimal class } 
$obj1 = new Item(); 
$obj2 = new Item(); 
print "\$obj1 is an ".gettype($obj1)."<br />"; 
print "\$obj2 is an ".gettype($obj2)."<br />"; 


2. Properties
class Item { var $name = "item"; } 
$obj1 = new Item(); 
$obj2 = new Item();
$obj1->name = "widget 5442"; 
print "$obj1->name<br />"; 
print "$obj2->name<br />"; 
// prints: 
// widget 5442 
// item 


3. Methods
<?php 
class Item {
var $name = "item";
function getName() {
return "item"; 
}
}
$item = new Item ();
print $item->getName (); 
// outputs "item“
 ?> 


4. Accessing Class Properties in a Method
<?php
class Item {
var $name = "item";
function getName () {
return $this->name;
}
}
$item = new Item ();
$item->name = "widget 5442";
print $item->getName ();
// outputs "widget 5442" 14: 
?> 


5. Constructors
<?php
class Item {
var $name; 
function Item( $name="item") {
$this->name = $name;

function setName( $n) { 
$this->name = $n; 
}
function getName () { 
return $this->name; 
}
}
$item = new Item("widget 5442"); 
print $item->getName ();
// outputs "widget 5442“
?> 
function __construct( $name="listing") { // ..} 


6. Property Declaration Keywords
public 
-Accessible to all. Equivalent to var.
private
-Available only to the containing class.
protected
-Available only to the containing class and subclasses.


Declaration – an example
public $name; 
private $code; 
protected $productString; 


7. Inheritance
<?php 
class Item {
var $name; 
function Item( $name="item", $code=0) { 
$this->name = $name; 
$this->code = $code; 
}
function getName() { 
return $this->name; 
}
}
class PriceItem extends Item {
}
$item = new PriceItem( "widget", 5442 );
print $item->getName ();
 // outputs "widget"
?> 


8. Objects and Constants
define global constants using the define() function
class MyClass { 
const PI = 3.14; //... 
Constants are available via the class rather than an object:
print MyClass::PI; 


9. Static Properties
static property is available via the class rather than the object 
class Item { public static $SALES_TAX=9; //... 
Notice that we can also determine the access level for a static property. We access the static class property via the class name:


Example
print "the tax to be levied on all items is"; 
print Item::$SALES_TAX."%"; 


10. Static Methods
static function doOperation() { //... 
Example
class Item { 
public static $SALES_TAX=10; 
private $name; 
public static function calcTax( $amount ) 
{ return ( $amount + ( $amount/(Item::$SALES_TAX/100)) ); 
} }
$amount = 10; 
print "given a cost of $amount, the total will be"; 
print Item::calcTax( $amount ); 
//prints "given a cost of 10, the total will be 110"  


11. Private constructors 
<?php 
class Shop { 
private static $instance; 
public $name="shop";
private function ___construct() { } 
?> 


12. Using Static Methods and Properties to Limit Instances of a Class 
<?php 
class Shop { 
private static $instance; 
public $name="shop";
private function ___construct() { } 
public static function getInstance() {
if ( empty( self::$instance ) ) { 
self::$instance = new Shop(); } 
return self::$instance; } }
$first = Shop::getInstance(); 
$first-> name="Acme Shopping Emporium"; 
$second = Shop::getInstance(); 
print $second -> name; 
?> 


13. Intercepting Calls to Object Properties and Methods
__call() 
this method will be invoked every time an undeclared method is called on your object, 
__get() 
called whenever client code attempts to access a property that is not explicitly defined 
__set() 
called when client code attempts to assign a value to a property that has not been explicitly defined 


14. __call() – an example
class Item {
  public $name = "item";
  public $price = 0;
  function __call( $method, $args ) {
    $bloggsfuncs = array ( "bloggsRegister", "bloggsRemove" );
    if ( in_array( $method, $bloggsfuncs ) ) {
      array_unshift( $args, get_object_vars( $this ) );
      return call_user_func( $method, $args );
    }
  }
}
$item = new Item();
print $item->bloggsRegister( true );
print $item->bloggsRemove( true );


15. __get() & __set() – an example
class TimeThing {
   function __get( $arg ) {
     if ( $arg == "time" ) {
       return getdate();
     }  }
   function __set( $arg, $val ) {
     if ( $arg == "time" ) {
       trigger_error( "cannot set property $arg" );
       return false;
     }   } }
 $cal = new TimeThing();
 print $cal->time['mday']."/";
 print $cal->time['mon']."/";
 print $cal->time['year'];
 $cal->time = 555; // illegal call


16. Final Methods  
class Item { 
private $id = 555; 
final function getID() 
{ return $this->id; } }


class PriceItem extends Item { 
function getID() { return 0; } }


It generates the following error:
Fatal error: Cannot override final method item::getid() 


17. Cleaning using Destructors
__destruct() 
automatically called when an object is about to be expunged from memory 
Example
class Item {   
public $name = "item";   
private $updater;   
public function setUpdater( ItemUpdater $update ) {
$this->updater=$update;   }   
function __destruct() {    
 if ( ! empty( $this->updater )) {       
$this->updater->update( $this );     
}   } } 


18. Cleaning using Destructors
<?php
 class ItemUpdater {
   public function update( Item $item ) {
     print "updating.. ";
     print $item->name;
   }
 }
 class Item {
   public $name = "item";
   private $updater;
   public function setUpdater( ItemUpdater $update ) {
     $this->updater=$update;
   }
   function __destruct() {
     if ( ! empty( $this->updater )) {
       $this->updater->update( $this );
     }
   }
 }
 $item = new Item();
 $item->setUpdater( new ItemUpdater() ) ;
 unset( $item );


19. Managing Error Conditions with Exceptions
exception 
an object that can be automatically populated with information about the error that has occurred and its script context 
You must instantiate Exception objects yourself with the new keyword just as you would with any object. Once you have an Exception object, you can literally throw it back to the client code 


20. Managing Error Conditions with Exceptions – an example
function doThing() {
  // uh oh. Trouble!
  throw new Exception( "A generic error", 666 );
  print "this will never be executed";
}


$test = new ThingDoer();
$test->doThing();


We run into the following error:
Fatal error: Uncaught exception 'exception'! in Unknown on line 0


21. Managing Error Conditions with Exceptions – an example
function doThing() {
  // uh oh. Trouble!
  throw new Exception( "A generic error", 666 );
  print "this will never be executed";
}


try {
  $test = new ThingDoer();
  $test->doThing();
} catch ( Exception $e ) {
  print $e->getMessage();
}


22. Exceptions - methods   
An Exception object has the following methods:
function exception( $message, $errorcode );
function getmessage(); 
function getcode(); 
function getfile(); 
function getline(); 
You can use them to construct error messages.


23. Defining Custom Exception Classes 
<?php
 class MyException extends Exception {
   public function summarize() {
     $ret = "<pre>\n";
     $ret .=  "msg: ".$this-> getMessage()."\n"
          ."code: ".$this->getCode()."\n"
          ."line: ".$this->getLine()."\n"
          ."file: ".$this->getFile()."\n";
     $ret .= "</pre>\n";
     return $ret;   } }
class FileNotFoundException extends MyException { }
class FileOpenException extends MyException {}
class Reader {
   function getContents( $file ) {
     if ( ! file_exists( $file ) ) {
       throw new FileNotFoundException( "could not find '$file'" );     }
     $fp = @fopen( $file, 'r' );
     if ( ! $fp ) {
       throw new FileOpenException( "unable to open '$file'" );
}
     while ( ! feof( $fp ) ) {
       $ret .= fgets( $fp, 1024 );
     }
     fclose( $fp );
     return $ret;
   }
 } 
$reader = new Reader();
 try {
   print $reader->getContents( "blah.txt" );
 } catch ( FileNotFoundException $e ) {
   print $e->summarize();
 } catch ( FileOpenException $e ) {
   print $e->summarize();
 } catch ( Exception $e ) {
   die("unknown error");
 }
?>


24. Abstract Classes
abstract class ItemUpdater {
}
The effect is that it is now impossible to directly instantiate an ItemUpdater object. Notice the following line:
$updater = new ItemUpdater();
It results in the following error:
Fatal error: Cannot instantiate abstract class Itemupdater


25. Abstract Classes – template methods
abstract class OutputComponent {
abstract function getComponentText();
abstract function filterComponentText( $txt );
abstract function writeComponentText();


final  function doOutput() {
    $txt = $this->getComponentText();
    $txt = $this->filterComponentText( $txt );
    $this->writeComponentText( $txt );
  }
}


26. Interfaces 
syntax
interface Serializable {
  function writeObject();
}


 How to use
class User extends Person implements Costable {
  // ...
}


27. Passing and Assigning Objects
class PassObj {
  function PassObj( $item ) {
    $item->name="harry";
  }}


class Item {
  var $name = "bob";
}
$item = new Item();
$pass = new PassObj( $item );
print $item->name;
///////////////////////////////////////////////////
function & addItem( &$item ) {
  $this->items[] = &$item;
  return $item;
}

No comments:

Post a Comment