欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php的面向对象

程序员文章站 2024-01-30 22:35:28
...
以下将涵盖php面向对象的主要知识点:

创建classname.php

$name;
    }
    public function __set($name,$value){
        if(($name="attribute") && ($value>=0) && ($valueattribute=$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(反射)API require_once ("TLA/page.inc"); $class=new ReflectionClass("Page"); echo "
".$class."
";

以上就介绍了php的面向对象,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。