在php中,类型的继承使用extends关键字,而且最多只能继承一个父类,php不支持多继承。这篇文章主要介绍了php中的类与对象(继承),需要的朋友可以参考下
简介
在php中,类型的继承使用extends关键字,而且最多只能继承一个父类,php不支持多继承。
class MyClass
{
public $dat = 0;
public function __construct($dat) {
$this->dat = $dat;
}
public function getDat() {
return "$this->dat\n";
}
}
class MySubClass extends MyClass
{
public function getDat() {
return "dat: $this->dat\n";
}
}
$a = new MyClass(3);
$b = new MySubClass(4);
echo $a->getDat(); // 3
echo $b->getDat(); // dat: 4
方法覆盖
包括构造函数在内,子类可以重新定义同名的类方法以覆盖父类方法。覆盖时遵循以下规则:
1.除构造函数之外,其他函数在覆盖时,函数的参数列表必须相同
2.包括构造函数在内,方法被覆盖后,调用子类方法时并不会自动调用父类方法
3.如果父类要禁止方法被子类覆盖,可以使用final来声明方法,这时如果子类仍要覆盖父类方法,将会出错
class MyClass
{
private $name = "";
public $num = 0;
public $str = "";
public function __construct($name) {
$this->name = $name;
$this->num = 100;
$this->str = "none";
}
public function getName() {
return $this->name;
}
}
class MySubClass extends MyClass
{
public function __construct($name, $str) {
parent::__construct($name); // 调用父类方法
$this->num = "0";
$this->str = $str;
echo parent::getName()."\n"; // 调用父类方法
}
public function getName() {
return parent::getName()."$this->str\n"; // 调用父类方法
}
}
$b = new MySubClass("myName", true); // myName
echo $b->getName(); // myName1
class MyClass
{
final public function getName() {
}
}
属性重定义
在子类中,可以访问父类中的public和protected属性成员,除非重定义了同名的自有属性,这时,父类中的属性将无法访问。
方法则不同,子类对方法进行覆盖后,仍然可以访问到父类方法。
class MyClass
{
public $a = 1;
protected $b = 2;
private $c = 3;
public function f1() {
echo "MyClass f1\n";
echo "\$a:$this->a; \$b:$this->b; \$c:$this->c;\n";
}
protected function f2() {
echo "MyClass f2\n";
echo "\$a:$this->a; \$b:$this->b; \$c:$this->c;\n";
}
private function f3() {
echo "MyClass f3\n";
}
}
class MySubClass extends MyClass
{
public $b = 22;
public $c = 33;
public function f1() {
echo "MySubClass f1\n";
// 继承到父类中的$a属性,直接使用
echo "\$a:$this->a; \$b:$this->b; \$c:$this->c;\n";
// 调用父类中的同名方法
parent::f1();
// 继承到父类中的f2()方法,直接使用
$this->f2();
}
// 父类的f3()是私有的,这里的定义与父类无关
public function f3() {
echo "MySubClass f3\n";
}
}
$b = new MySubClass;
$b->f1();echo "\n";
/*
MySubClass f1
$a:1; $b:22; $c:33;
MyClass f1
$a:1; $b:22; $c:3;
MyClass f2
$a:1; $b:22; $c:3;
*/
$b->f3();echo "\n";
/*
MySubClass f3
*/
重定义父类(同名)属性时,属性的可访问性可以变得更开放,但不能更严格,也就是说,父类中的public属性,不能在子类中修改为private属性。
如果通过子类对象调用父类方法,那么该父类方法在访问属性时,对于重定义了的同名属性,public和protected的属性将访问到子类版本,private属性将访问到父类版本。也可以理解为,public和protected属性可以被重定义(父类的版本被重定义,从而不存在了),而private并未被重定义(父类中的属性仍然存在,通过父类方法进行访问,与子类中是否有同名属性毫不相干)。
class MyClass
{
public $a = 1;
protected $b = 2;
private $c = 3;
public function f1() {
echo "\$a:$this->a; \$b:$this->b; \$c:$this->c;\n";
}
}
class MySubClass extends MyClass
{
public $a = 11; // 必须为public
protected $b = 22; // 必须为protected或public
private $c = 33;
public function f2() {
echo "\$a:$this->a; \$b:$this->b; \$c:$this->c;\n";
}
}
$b = new MySubClass;
$b->f1(); // $a:11; $b:22; $c:3;
$b->f2(); // $a:11; $b:22; $c:33;
范围解析操作符 ::
又冒号常用于访问类常量、类静态变量,也用于在方法覆盖时调用父类版本。与其搭配的还包括parent、self、static等关键字。
class MyClass
{
const Name0 = "MyClass"; // 类常量
public static $id0 = 0; // 类变量
public function put() { // 将被子类覆盖的方法
echo "MyClass put()\n";
}
}
class MySubClass extends MyClass
{
const Name1 = "MySubClass";
public static $id1 = 1;
public function put() {
parent::put(); // 调用父类版本的对象方法
echo parent::Name0 . "\n"; // 父类常量
echo parent::$id0 . "\n"; // 父类变量
echo self::Name1."\n"; // 子类常量
echo self::$id1 . "\n"; // 子类变量
echo static::Name1 . "\n"; // 子类常理
echo static::$id1 . "\n"; // 子类变量
}
}
$a = "MyClass";
$ca = new MyClass;
$cb = new MySubClass;
$cb->put();
echo MyClass::Name0 . "\n";
echo MyClass::$id0 . "\n";
echo $a::Name0 . "\n";
echo $a::$id0 . "\n";
echo $ca::Name0 . "\n";
echo $ca::$id0 . "\n";
在子类中访问父类中的成员时,应避免直接使用父类类名,而应使用parent::,以免破坏父类的封装性。
final
声明为final的方法不能被子类覆盖,如果类声明为final,则此类不能被继承。
// 声明为final的类不能被继承
final class MyClass
{
private $dat;
public function __construct($dat) {
$this->dat = $dat;
}
// final方法不能被覆盖,不过此类已经是final类,方法无必要在声明为final了
final public function getDat() {
return $this->dat;
}
}
总结
以上所述是小编给大家介绍的php中的类与对象(继承),希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对php中文网的支持!
您可能感兴趣的文章:
The above is the detailed content of Detailed explanation of classes and objects in php. For more information, please follow other related articles on the PHP Chinese website!
How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AMPHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.
How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AMIn PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.
PHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AMPHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.
Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Apr 17, 2025 am 12:22 AMKey players in HTTP cache headers include Cache-Control, ETag, and Last-Modified. 1.Cache-Control is used to control caching policies. Example: Cache-Control:max-age=3600,public. 2. ETag verifies resource changes through unique identifiers, example: ETag: "686897696a7c876b7e". 3.Last-Modified indicates the resource's last modification time, example: Last-Modified:Wed,21Oct201507:28:00GMT.
Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Apr 17, 2025 am 12:06 AMIn PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.
PHP: An Introduction to the Server-Side Scripting LanguageApr 16, 2025 am 12:18 AMPHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.
PHP and the Web: Exploring its Long-Term ImpactApr 16, 2025 am 12:17 AMPHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.
Why Use PHP? Advantages and Benefits ExplainedApr 16, 2025 am 12:16 AMThe core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1
Powerful PHP integrated development environment

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.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

WebStorm Mac version
Useful JavaScript development tools







