PHP/Class/this

Материал из Web эксперт
Перейти к: навигация, поиск

Accessing the $age variable using this->

   <source lang="html4strict">

<?php class Cat {

   var $age;
   function Cat($new_age){
       $this->age = $new_age;
   }
   function Birthday(  ){
       $this->age++;
   }

} $fluffy = new Cat(1); echo "Age is $fluffy->age
"; echo "Birthday
"; $fluffy->Birthday( ); echo "Age is $fluffy->age
"; ?>

 </source>
   
  


$this keyword refers to the instance from within the class definition

   <source lang="html4strict">

<?php

 class Bird
 {
   function __construct($name, $breed)
   {
     $this->name = $name;
     $this->breed = $breed;
   }
 }
 $tweety = new Bird("Tweety", "canary");
printf("

%s is a %s.

\n", $tweety->name, $tweety->breed);

?>

 </source>
   
  


Use this keyword

   <source lang="html4strict">

<?php

  class Staff
  {
     var $name;
     var $city;
     protected $wage;
     function __get($propName)
     {
        echo "__get called!
"; $vars = array("name","city"); if (in_array($propName, $vars)) { return $this->$propName; } else { return "No such variable!"; } } } $employee = new Staff(); $employee->name = "Joe"; echo $employee->name."
"; echo $employee->age;

?>

      </source>
   
  


Use this keyword to reference interal properties

   <source lang="html4strict">

<?php class Employee {

   public $numPages;
   public $stayYear;
   public $title;
   public $lastName;
   public $firstName;
   public $price;
   
   function __construct(   $title, $firstName, 
                           $mainName, $price, 
                           $numPages=0, $stayYear=0 ) { 
       $this->title             = $title;
       $this->firstName = $firstName;
       $this->lastName  = $mainName;
       $this->price     = $price;
       $this->numPages  = $numPages;
       $this->stayYear = $stayYear;
   }
   
   function getNumberOfPages() {
       return $this->numPages;
   }
   function getStayLength() {
       return $this->stayYear;
   }
   function getFullName() {
       return "{$this->firstName}" .  "{$this->lastName}";
   }

} $product1 = new Employee("A", "A1", "A2", 5.99, 300 ); $product2 = new Employee("B", "B1", "B2", 10.99, null, 60.33 ); print "author: ".$product1->getFullName()."\n"; print "number of pages: ".$product1->getNumberOfPages()."\n"; print "artist: ".$product2->getFullName()."\n"; print "play length: ".$product2->getStayLength()."\n"; ?>


      </source>