Home > php教程 > php手册 > PHP 重载

PHP 重载

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-13 09:18:19
Original
1493 people have browsed it

PHP 重载

PHP 重载

一个类中的方法与另一个方法同名,但是参数不同,这种方法称之为重载方法。

很遗憾因为 PHP 是弱类型的语言, 所以在方法的参数中本身就可以接收不同类型的数据,又因为 PHP 的方法可以接收不定个数的参数,所以在 PHP 里面没有严格意义上的方法重载。

PHP 中的重载是指在子类里面定义了一个和父类同名的方法,且该方法将在子类中将把父类的方法覆盖。

在子类中,因为从父类继承过来的方法可能无法访问子类定义的属性或方法,所以有时候重载是必要的。

例子:

<?php
class Person {
    var $name;
    var $age;

    function say() {
        echo "我的名字叫:".$this->name."<br />";
	echo "我的年龄是:".$this->age;
    }
}

// 类的继承
class Student extends Person {
    var $school;    //学生所在学校的属性
	
    function say() {
        echo "我的名字叫:".$this->name."<br />";
        echo "我的年龄是:".$this->age."<br />";
        echo "我正在".$this->school."学习";
    }	
}

$t1 = new Student();
$t1->name = "张三";
$t1->age = "18";
$t1->school = "人民大学";
$t1->say();
?>
Copy after login

运行该例子,输出:

我的名子叫:张三
我的年龄是:18
我正在人民大学学习
Copy after login

提示

如果父类定义方法时使用了 final 关键字,则不允许被子类方法覆盖。

访问父类被覆盖的方法

可以通过 :: 符号来访问父类被覆盖的方法或成员属性:

function say() {
    parent::say();
    //或者
    Person::say();
    echo "我在".$this->school."上学<br />";
}
Copy after login

范围解析操作符 :: 用法参见《PHP 范围解析操作符 ::》。

Related labels:
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
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template