PHP/Class/private
Содержание
- 1 Access private properties with for each loop
- 2 Changing the member $a to protected or private
- 3 class member variable access: private
- 4 If the variable was defined as private static, it would not be possible to access it directly
- 5 Private and inheritance
- 6 Private properties are accessible only inside the methods of the class that defined them
- 7 Protect the class from being misused by accessing the members directly
- 8 Using private and public in Classes
Access private properties with for each loop
<source lang="html4strict">
<?
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( );
?>
</source>
Changing the member $a to protected or private
<source lang="html4strict">
<?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"; ?>
</source>
class member variable access: private
<source lang="html4strict">
<?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"); } }
?>
</source>
If the variable was defined as private static, it would not be possible to access it directly
<source lang="html4strict">
<?php class myclass {
const MYCONST = 123; private static $value = 567;
} echo "myclass::MYCONST = " . myclass::MYCONST . "\n"; echo "myclass::$value = " . myclass::$value . "\n"; ?>
</source>
Private and inheritance
<source lang="html4strict">
<?
class Dog { private $Name; } class Poodle extends Dog { } $poppy = new Poodle; $poppy->Name = "Poppy"; print_r($poppy);
?>
</source>
Private properties are accessible only inside the methods of the class that defined them
<source lang="html4strict">
<?
class Dog { private $Name; private $DogTag; public function setName($NewName) { // etc } }
?>
</source>
Protect the class from being misused by accessing the members directly
<source lang="html4strict">
<?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"; ?>
</source>
Using private and public in Classes
<source lang="html4strict">
<?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;
?>
</source>