本文章来详细介绍PHP 类的变量与成员,及其继承、访问与重写要注意问题,有需要的朋友可参考参考。
基于 PHP5.3
PHP 的类及其实例:
代码如下 | 复制代码 |
public $prop = 123; } $obj = new Myclass(); |
类的成员属性(属性的称呼相对于“方法”而言)包括类常量和类变量,其中类常量在定义时不可为空,类的属性在定义时如果被赋值,只能使用标量和数组,并且不能是表达式,因为类属性在编译期被初始化,PHP 在编译期不执行表达式。
1、成员的访问控制:
public:可以继承,可以在类的方法之外被访问 , 如 $obj->prop;
protected:可以继承,不可以在类的方法之外被访问
private:不可以继承,不可以在类的方法之外访问
PHP 4 使用 var 来声明类的属性,在PHP5之后不再使用,PHP5.3之前使用被警告,PHP5.3之后可以用在 public 之前或单独使用作为 public 的别名。
这三个访问控制关键字也可以修饰构造函数,当 private 和 protected 修饰类的构造函数时,你只能通过一个 publice static 的静态方法来调用构造函数以实例化对象,因为够在函数无法在类之外被访问了,比如,单例类的实现:
代码如下 | 复制代码 |
class Singleton { } public static function getInstance(){ return self::$instance; public function __clone(){ //pretend clone oprationg //new Singleton(); // Error
|
2、继承禁止: final 关键字,仅用于修饰类或类的方法
如果一个类被 final 修饰,这个类不能被继承,如果一个方法被final 修饰,则这个方法不能被子类重写(override)。
代码如下 | 复制代码 |
class Myclass{ public $prop = 123; final public static function methodA(){//不可继承的,公开的静态方法 return 'this is a final method'; } } |
3、抽象类和抽象方法:abstract 仅用于 类和方法,抽象类不能直接用于实例化对象只能用于产生子类
代码如下 | 复制代码 |
abstract class Myclass{ public $prop = 123; abstract public function methodA(); //抽象方法没有实现函数体 } |

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download
The most popular open source editor

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version
Visual web development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment
