PHP新手之学习类与对象(1)

本文介绍的是PHP程序设计语言中类和对象的基本知识,适合初学者阅读,希望对你有帮助,一起来看。

PHP 5 引入了新的对象模型(Object Model)。完全重写了 PHP 处理对象的方式,允许更佳性能和更多特性。

一、基本概念

1、class

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

Example#1 面向对象语言中的 $this 变量

<?php
class A {
    function foo() {
        if (isset($this)) {
            echo '$this is defined (';
            echo get_class($this);
            echo ")
";
        } else {
            echo "$this is not defined.
";
        } 
    } 
} 
class B {
    function bar() {
        A :: foo();
    } 
} 
$a = new A();
$a -> foo();
A :: foo();
$b = new B();
$b -> bar();
B :: bar();

?>

上例将输出:

  1. $this is defined (a)  
  2. $this is not defined.  
  3. $this is defined (b)  
  4. $this is not defined. 

Example#2 简单的类定义

<?php
class SimpleClass {
    // 成员声明
    public $var = 'a default value';
    // 方法声明
    public function displayVar() {
        echo $this -> var;
    } 
} 

?>

Example#3 类成员的默认值

<?php
class SimpleClass {
    // 无效的类成员定义:
    public $var1 = 'hello ' . 'world';
    public $var2 = <<<EOD
hello world
EOD;
    public $var3 = 1 + 2;
    public $var4 = self :: myStaticMethod();
    public $var5 = $myVar;
    // 正确的类成员定义:
    public $var6 = myConstant;
    public $var7 = self :: classConstant;
    public $var8 = array(true, false);
} 

?>

2、new

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

Example#4 创建一个实例

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

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

Example#5 对象赋值

<?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);

?>

复制代码上例将输出:

  1. NULL  
  2. NULL  
  3. object(SimpleClass)#1 (1) {  
  4. ["var"]=
  5. string(30) "$assigned will have this value"  

3、extends

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

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

Example#6 简单的类继承

<?php
class ExtendClass extends SimpleClass {
    // Redefine the parent method
    function displayVar() {
        echo "Extending class
";
        parent :: displayVar();
    } 
} 
$extended = new ExtendClass();
$extended -> displayVar();

?>

上例将输出:

  1. Extending class  
  2. a default value 
原文地址:https://www.cnblogs.com/qingsong/p/5351079.html