PHP/Class/private — различия между версиями

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

Текущая версия на 07:00, 26 мая 2010

Access private properties with for each loop

 
<?
    class Person {
            public $FirstName = "B";
            public $MiddleName = "T";
            public $LastName = "M";
            private $Password = "asdfasdf";
            public $Age = 29;
            public $HomeTown = "LA";
            public $FavouriteColor = "Purple";
            public function outputVars( ) {
                    foreach($this as $var => $value) {
                            echo "$var is $value\n";
                    }
            }
    }
    $bill = new Person( );
    $bill->outputVars( );
?>



Changing the member $a to protected or private

 
<?php
class myclass {
  private $a;
  
  function set_value($val) {
    $this->a = $val;
  }
}
$obj = new myclass;
$obj->set_value(123);
echo "Member a = $obj->a\n";
$obj->a = 7;
echo "Member a = $obj->a\n";
?>



class member variable access: private

<?php
   class Staff
   {
      private $name;
      private $title;
      protected $wage;
      protected function clockIn() {
         echo "Member $this->name clocked in at ".date("h:i:s");
      }
   
      protected function clockOut() {
         echo "Member $this->name clocked out at ".date("h:i:s");
      }
   }
?>



If the variable was defined as private static, it would not be possible to access it directly

 
<?php 
class myclass { 
    const MYCONST = 123; 
    private static $value = 567; 
} 
echo "myclass::MYCONST = " . myclass::MYCONST . "\n"; 
echo "myclass::$value = " . myclass::$value . "\n"; 
?>



Private and inheritance

 
<?
    class Dog {
            private $Name;
    }
    class Poodle extends Dog { }
    $poppy = new Poodle;
    $poppy->Name = "Poppy";
    print_r($poppy);
?>



Private properties are accessible only inside the methods of the class that defined them

 
<?
    class Dog {
            private $Name;
            private $DogTag;
            public function setName($NewName) {
                    // etc
            }
    }
?>



Protect the class from being misused by accessing the members directly

 
<?php
class myclass {
  private $a;
  
  function set_value($val) {
    $this->a = $val;
  }
  function get_value() {
    return $this->a;
  }
}
$obj = new myclass;
$obj->set_value(123);
echo "Member a = " . $obj->get_value() . "\n";
?>



Using private and public in Classes

 
<?php
     class myPHP5Class {
          private $my_variable;
          public function my_method($param) {
               echo "my_method($param)!\n";
               echo "my variable is: ";
               echo "{$this->my_variable}\n";
          }
     }
     $myobject = new myPHP5Class();
     $myobject->my_method("MyParam");
     $myobject->my_variable = 10;
?>