PHP面向对象程序设计高级特性详解(接口,继承,抽象类,析构,克隆等)
(编辑:jimmy 日期: 2025/4/20 浏览:3 次 )
本文实例讲述了PHP面向对象程序设计高级特性。分享给大家供大家参考,具体如下:
静态属性
<"hello"; } } print StaticExample::$aNum; StaticExample::sayHello(); "htmlcode"><"hello (".self::$aNum.")\n"; // self 指向当前类, $this指向当前对象。 } } StaticExample::sayHello(); StaticExample::sayHello(); StaticExample::sayHello(); "htmlcode">hello (1) hello (2) hello (3)点评:self 指向当前类, this指向当前对象。self可以调用当前类的静态属性和方法。this指向当前对象。self可以调用当前类的静态属性和方法。this可以调用当前类的正常属性和方法。
常量属性
<"htmlcode"><"color: #ff0000">Fatal error: Class ShopProduct contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (Chargeable::getPrice)继承类与接口
<"htmlcode"><"htmlcode">Document Object ( )静态方法
<"default"; } } class User extends DomainObject { } class Document extends DomainObject { static function getGroup() { // 改变了内容 return "document"; } } class SpreadSheet extends Document { // 继承之后,group也就与document相同了 } print_r(User::create()); print_r(SpreadSheet::create()); "htmlcode">User Object ( [group:DomainObject:private] => default ) SpreadSheet Object ( [group:DomainObject:private] => document )final字段
使类无法被继承,用的不多
<"color: #ff0000">Fatal error: Class IllegalCheckout may not inherit from final class (Checkout)final方法不能够被重写
<"color: #ff0000">Fatal error: Cannot override final method Checkout::totalize()析构函数
<"saving person\n"; } if ( empty( $this->id ) ) { // save Person data print "do nothing\n"; } } } $person = new Person( "bob", 44 ); $person->setId( 343 ); $person->setId( '' ); // 最后执行析构函数,使用完之后执行 "color: #ff6600">克隆的时候执行<"bob", 44 ); $person->setId( 343 ); $person2 = clone $person; print_r( $person ); print_r( $person2 ); "htmlcode">Person Object ( [name:Person:private] => bob [age:Person:private] => 44 [id:Person:private] => 343 ) Person Object ( [name:Person:private] => bob [age:Person:private] => 44 [id:Person:private] => 0 )再看一个例子
上一篇:PHP面向对象继承用法详解(优化与减少代码重复)<"bob", 44, new Account( 200 ) ); // 以类对象作为参数 $person->setId( 343 ); $person2 = clone $person; // give $person some money $person->account->balance += 10; // $person2 sees the credit too print $person2->account->balance; // person的属性account也是一个类,他的属性balance的值是210 // output: // 210 "htmlcode"><"Bob"; } function getAge() { return 44; } function __toString() { $desc = $this->getName()." (age "; $desc .= $this->getAge().")"; return $desc; } } $person = new Person(); print $person; // 打印时候集中处理 // Bob (age 44) "_blank" href="https://www.jb51.net/Special/43.htm">php面向对象程序设计入门教程》、《PHP基本语法入门教程》、《PHP运算与运算符用法总结》、《PHP网络编程技巧总结》、《PHP数组(Array)操作技巧大全》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》希望本文所述对大家PHP程序设计有所帮助。
下一篇:PHP面向对象程序设计之命名空间与自动加载类详解
在去年的5月23日,借助Intel Bridge Technology以及Intel Celadon两项技术的驱动,Intel为PC用户带来了Android On Windows(AOW)平台,并携手国内软件公司腾讯共同推出了腾讯应用宝电脑版,将Windows与安卓两大生态进行了融合,PC的使用体验随即被带入到了一个全新的阶段。