基本概念

class

每个类的定义都以关键字 class 开头,后面跟着类名,可以是任何非 PHP 保留字 的名字。后面跟着一对花括号,里面包含有类成员和方法的定义。伪变量 $this 可以在当一个方法在对象内部调用时使用。 $this 是一个到调用对象(通常是方法所属于的对象,但也可以是另一个对象,如果该方法是从第二个对象内 静态 调用的话)的引用。看下面例子:

<?php
class A
{
    function
foo ()
    {
        if (isset(
$this )) {
            echo
'$this is defined (' ;
            echo
get_class ( $this );
            echo
")\n" ;
        } else {
            echo
"\$this is not defined.\n" ;
        }
    }
}

class
B
{
    function
bar ()
    {
        
A :: foo ();
    }
}

$a = new A ();
$a -> foo ();
A :: foo ();
$b = new B ();
$b -> bar ();
B :: bar ();
?>

上例将输出:

$this is defined (a)
$this is not defined.
$this is defined (b)
$this is not defined.

例子 19-1. 简单的类定义

<?php
class SimpleClass
{
    
// 成员声明
    
public $var = 'a default value' ;

    
// 方法声明
    
public function displayVar () {
        echo
$this -> var ;
    }
}
?>

new

要创建一个对象的实例,必须创建一个新对象并将其赋给一个变量。当创建新对象时该对象总是被赋值,除非该对象定义了 构造函数 并且在出错时抛出了一个 异常

例子 19-2. 创建一个实例e

<?php
$instance
= new SimpleClass ()
?>

当把一个对象已经创建的实例赋给一个新变量时,新变量会访问同一个实例,就和用该对象赋值一样。此行为和给函数传递入实例时一样。可以用 克隆 给一个已创建的对象建立一个新实例。

例子 19-3. 对象赋值

<?php
$assigned   
=   $instance ;
$reference   =& $instance ;

$instance -> var = '$assigned will have this value' ;

$instance = null ; // $instance and $reference become null

var_dump ( $instance );
var_dump ( $reference );
var_dump ( $assigned );
?>

上例将输出:

NULL
NULL
object(SimpleClass)#1 (1) {
   ["var"]=>
     string(30) "$assigned will have this value"
}

extends

一个类可以在声明中用 extends 关键字继承另一个类的方法和成员。不能扩展多个类,只能继承一个基类。

被继承的方法和成员可以通过用同样的名字重新声明被覆盖,除非父类定义方法时使用了 final 关键字。可以通过 parent:: 来访问被覆盖的方法或成员。

例子 19-4. 简单的类继承

<?php
class ExtendClass extends SimpleClass
{
    
// Redefine the parent method
    
function displayVar ()
    {
        echo
"Extending class\n" ;
        
parent :: displayVar ();
    }
}

$extended = new ExtendClass ();
$extended -> displayVar ();
?>

上例将输出:

Extending class
a default value