以下将涵盖php面向对象的主要知识点:
创建classname.php
<?php
//类的封装
class classname{
public $attribute;
public function __get($name){
return $this->$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 <br/>";
}
protected function operation2(){
echo "operation2 called <br/>";
}
public function operation3(){
echo "operation3 called <br/>";
}
function operation(){
echo "Something <br/>";
echo "The value of \$attribute is ". $this->attribute."<br/>";
}
}
//类的继承、重载
class B extends A{
public $attribute="different value";
function __construct(){
$this->operation2();
$this->operation3();
}
function operation(){
echo "Something else<br/>";
echo "The value of \$attribute is ". $this->attribute."<br/>";
}
}
//使用final关键字禁止继承和重载
class FinalA{
public $attribute="default value";
final function operation(){
echo "Something<br/>";
echo "The value of \$attribute is".$this->attribute."<br/>";
}
}
//实现接口
interface Displayable{
function display();
}
class webPage implements Displayable{
function display(){
echo "实现了接口<br/>";
}
}
//使用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
<?php
require_once 'classname.php';
//创建实例
$a=new classname();
$a->attribute=5;
//类的继承、重载
$b=new B();
$b->operation3();
echo "<br/>";
$b->operation();
//访问常量所属的类
echo "Math::pi=".Math::pi."<br/>";
//访问静态方法
echo Math::squared(8)."<br/>";
//检查类的类型和类型提示 instanceof关键字
if($b instanceof B){
echo "true <br/>";
}
function check_hint(B $someclass){
echo "right <br/>";
}
check_hint($b);
//延迟静态绑定
D::test();
echo "<br/>";
//克隆对象
$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."<br/>";
}
//使用Reflection(反射)API
require_once ("TLA/page.inc");
$class=new ReflectionClass("Page");
echo "<pre>".$class."</pre>";