以下將涵蓋php面向對象的主要知識點:
建立classname.php
$name; } public function __set($name,$value){ if(($name="attribute") && ($value>=0) && ($value<=100)){ $this->attribute=$value; } }}//存取修飾詞:private、protected、public;class A{ public $attribute="default value"; private function operation1(){ echo "operation1 called
"; } protected function operation2(){ echo "operation2 called
"; } public function operation3(){ echo "operation3 called
"; } function operation(){ echo "Something
"; echo "The value of \$attribute is ". $this->attribute."
"; }}//類的繼承、重載class B extends A{ public $attribute="different value"; function __construct(){ $this->operation2(); $this->operation3(); } function operation(){ echo "Something else
"; echo "The value of \$attribute is ". $this->attribute."
"; }}//使用final關鍵字禁止繼承和重載class FinalA{ public $attribute="default value"; final function operation(){ echo "Something
"; echo "The value of \$attribute is".$this->attribute."
"; }}//實現介面interface Displayable{ function display();}class webPage implements Displayable{ function display(){ echo "實現了介面
"; }}//使用Pre-class常量、實現靜態方法class Math{ //使用Pre-class常量 const pi=3.14159; //實現靜態方法 static function squared($input){ return $input*$input; }}//延遲靜態繫結class C{ public static function who(){ echo __CLASS__; } public static function test(){ static::who(); }}class D extends C{ public static function who(){ echo __CLASS__; }}//使用抽象類別abstract class E{ abstract function operationX($param1,$param2);}//使用__call()重載方法class Overload{ public function __call($method,$p){ if($method=="display"){ if(is_object($p[0])){ $this->displayObject($p[0]); }elseif(is_array($p[0])){ $this->displayArray($p[0]); }else{ $this->displayScalar($p[0]); } } }}//實現迭代器和迭代class myClass{ public $a="5"; public $b="7"; public $c="9";}//將類轉換成字串class Printable{ public $testone; public $testtwo; public function __toString(){ return(var_export($this,TRUE)); }}建立index.php
require_once 'classname.php';//建立執行個體$a=new classname();$a->attribute=5;//類的繼承、重載$b=new B();$b->operation3();echo "
";$b->operation();//訪問常量所屬的類echo "Math::pi=".Math::pi."
";//訪問靜態方法echo Math::squared(8)."
";//檢查類的類型和類型提示 instanceof關鍵字if($b instanceof B){ echo "true
";}function check_hint(B $someclass){ echo "right
";}check_hint($b);//延遲靜態繫結D::test();echo "
";//複製對象$c=clone $b;//使用__call()重載方法$ov=new Overload();$ov->display(array(1,2,3));$ov->display('cat');//使用__autoload()方法function __autoload($name){ include_once $name.".php";}//實現迭代器和迭代$x=new myClass();foreach($x as $attribute){ echo $attribute."
";}//使用Reflection(反射)APIrequire_once ("TLA/page.inc");$class=new ReflectionClass("Page");echo "".$class."
";
以上就介紹了php的物件導向,包括了方面的內容,希望對PHP教程有興趣的朋友有所協助。