Home > php教程 > PHP源码 > body text

PHP 类的变量与成员,及其继承、访问(1/3)

WBOY
Release: 2016-06-08 17:24:33
Original
1041 people have browsed it

本文章来详细介绍PHP 类的变量与成员,及其继承、访问与重写要注意问题,有需要的朋友可参考参考。

<script>ec(2);</script>

基于 PHP5.3

 PHP 的类及其实例:

 代码如下 复制代码


class Myclass{

   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 {
    private static $instance=null;
    public $k = 88;
    private function __construct(){

    }

    public static function getInstance(){
        if(self::$instance==null){
                self::$instance = new self();
        }

        return self::$instance;
    }

    public function  __clone(){ //pretend clone oprationg
        throw('Singleton class can not be cloned');
        return self::getInstance();
    }
}

//new Singleton();  // Error
$in = Singleton::getInstance();  

 

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(); //抽象方法没有实现函数体

}

首页 1 2 3 末页
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!