search
HomeBackend DevelopmentPHP TutorialQuick Fix 4 - PHP: Class Basics, Abstract Classes, Interfaces, Traits

[Source code download]

Quick Solution (4) - PHP: Class Basics, Abstract Classes, Interfaces, Traits


Author: webabcd
Introduction
Quick Solution to PHP

  • Class Basics
  • Abstract Class
  • Interface
  • trait


Example
1. Class-related knowledge point 1 (basic)
class/class1.php

<span>php
</span><span>/*</span><span>*
 * 类的相关知识点 1(基础)
 *
 * 规范:命名空间与目录路径对应,类名与文件名对应,文件以 .class.php 为后缀名
 </span><span>*/</span><span>class</span><span> MyClass1
{
    </span><span>//</span><span> 类常量,没有“$”符号,不能被覆盖</span><span>const</span> MyConstant = 'constant value'<span>;
    </span><span>//</span><span> 静态属性</span><span>static</span><span>$myStaticProperty</span> = "static property"<span>;

    </span><span>//</span><span> 对于属性和方法的访问控制有 private protected public(默认值)</span><span>private</span><span>$_name</span><span>;
    </span><span>private</span><span>$_age</span><span>;

    </span><span>//</span><span> 构造函数
    // PHP 中的魔术方法(magic method)均以 __(两个下划线)开头(类似的还有 __destruct(),__call(),__callStatic(),__get(),__set(),__isset(),__unset(),__sleep(),__wakeup(),__toString(),__invoke(),__set_state() 和 __clone() 等)</span><span>function</span><span> __construct()
    {
        </span><span>echo</span> "MyClass1 construct"<span>;
        </span><span>echo</span> "<br>"<span>;

        </span><span>//</span><span> 获取参数个数</span><span>$args_num</span> = <span>func_num_args</span><span>();

        </span><span>if</span> (<span>$args_num</span> == 1<span>)
        {
            </span><span>//</span><span> $this 代表当前对象,是指向类实例的指针</span><span>$this</span>->_name = <span>func_get_arg</span>(0<span>);
        }
        </span><span>else</span><span>if</span> (<span>$args_num</span> == 2<span>)
        {
            </span><span>$this</span>->_name = <span>func_get_arg</span>(0<span>);
            </span><span>$this</span>->_age = <span>func_get_arg</span>(1<span>);
        }
        </span><span>else</span><span>        {

        }
    }

    </span><span>//</span><span> 析构函数</span><span>function</span><span> __destruct()
    {
        </span><span>print</span> "MyClass1 destruct"<span>;
        </span><span>echo</span> "<br>"<span>;
    }

    </span><span>//</span><span> 构造函数,此种方式在 PHP 5.3.3 或以上可支持
    // 此种方式的构造函数也可以当做方法被调用</span><span>public</span><span>function</span><span> MyClass1()
    {
        </span><span>echo</span> "i am not a construct, i am a method"<span>;
    }

    </span><span>//</span><span> 静态方法</span><span>public</span><span>static</span><span>function</span><span> myStaticMethod()
    {
        </span><span>return</span> "static method"<span>;
    }

    </span><span>//</span><span> 方法</span><span>public</span><span>function</span><span> getInfo()
    {
        </span><span>//</span><span> $this 代表当前对象,是指向类实例的指针</span><span>return</span> "name: " . <span>$this</span>->_name . ", age: " . <span>$this</span>-><span>_age;
    }

    </span><span>//</span><span> 不直接支持方法的重载(overload),可以通过相关的魔术方法来实现(参见:class3.php)
    // public function getInfo($name) { }

    // 带参数类型约束的方法,类型约束不能用于 int 或 string 之类的标量类型
    // 本例约束了参数 $ary 必须是 array 类型</span><span>public</span><span>function</span> getFirst(<span>array</span><span>$ary</span><span>)
    {
        </span><span>return</span><span>$ary</span>[0<span>];
    }
}

</span><span>//</span><span> 被声明为 final 的类或属性或方法,无法继承
// 只能继承一个类</span><span>final</span><span>class</span> MyClass2 <span>extends</span><span> MyClass1
{
    </span><span>//</span><span> 构造函数可以为参数设置默认值(方法或函数也可以为参数设置默认值)</span><span>function</span> __construct(<span>$name</span> = "wanglei", <span>$age</span> = 100<span>)
    {
        </span><span>echo</span> "MyClass2 construct"<span>;
        </span><span>echo</span> "<br>"<span>;

        </span><span>//</span><span> parent 代表当前类的基类</span>        parent::__construct(<span>$name</span>, <span>$age</span><span>);

        </span><span>//</span><span> self 代表当前类
        // $this 代表当前对象,是指向类实例的指针</span><span>    }

    </span><span>//</span><span> 析构函数</span><span>function</span><span> __destruct()
    {
        </span><span>print</span> "MyClass2 destruct"<span>;
        </span><span>echo</span> "<br>"<span>;

        parent</span>::<span>__destruct();
    }

    </span><span>//</span><span> 覆盖基类的同名方法(override)</span><span>public</span><span>function</span><span> getInfo()
    {
        </span><span>//</span><span> $this 代表当前对象,指向类实例的指针</span><span>return</span> "MyClass2 - " . parent::<span>getInfo();
    }
}

</span><span>//</span><span> 类的实例化</span><span>$objClass1</span> = <span>new</span> MyClass1("webabcd", 35<span>);
</span><span>//</span><span> 通过 -> 调用实例方法或实例属性</span><span>echo</span><span>$objClass1</span>-><span>getInfo();
</span><span>echo</span> "<br>"<span>;
</span><span>//</span><span> 通过 -> 调用实例方法或实例属性(MyClass1() 是构造函数,也可以当做方法被调用)</span><span>echo</span><span>$objClass1</span>-><span>MyClass1();
</span><span>echo</span> "<br>"<span>;

</span><span>$objClass2</span> = <span>new</span><span> MyClass2();
</span><span>echo</span><span>$objClass2</span>-><span>getInfo();
</span><span>echo</span> "<br>"<span>;

</span><span>//</span><span> instanceof - 用于判断一个对象是否是指定类的实例</span><span>if</span>(<span>$objClass2</span><span> instanceof MyClass1)
{
    </span><span>echo</span> '$objClass2 instanceof MyClass1'<span>;
    </span><span>echo</span> "<br>"<span>;
}

</span><span>//</span><span> 通过 :: 调用类常量或静态属性或静态方法</span><span>echo</span> MyClass1::<span>MyConstant;
</span><span>echo</span> "<br>"<span>;

</span><span>//</span><span> 通过 :: 调用类常量或静态属性或静态方法</span><span>echo</span> MyClass1::<span>$myStaticProperty</span><span>;
</span><span>echo</span> "<br>"<span>;

</span><span>//</span><span> variable class(可变类),将变量的值作为类名</span><span>$className</span> = 'MyClass1'<span>;
</span><span>//</span><span> variable method(可变方法),将变量的值作为方法名</span><span>$methodName</span> = 'myStaticMethod'<span>;
</span><span>//</span><span> 通过 :: 调用类常量或静态属性或静态方法</span><span>echo</span><span>$className</span>::<span>$methodName</span><span>();
</span><span>echo</span> "<br>"<span>;

</span><span>//</span><span> 调用带参数类型约束的方法</span><span>echo</span><span>$objClass1</span>->getFirst(<span>array</span>("a", "b", "c"<span>));
</span><span>echo</span> "<br>";


2. Class-related knowledge point 2 (abstract class, interface, trait)
class/class2.php

<span>php
</span><span>/*</span><span>*
 * 类的相关知识点 2(抽象类,接口,trait)
 </span><span>*/</span><span>//</span><span> 抽象类</span><span>abstract</span><span>class</span><span> MyAbstractClass
{
    </span><span>//</span><span> 抽象方法,子类必须定义这些方法</span><span>abstract</span><span>protected</span><span>function</span><span> getValue1();
    </span><span>abstract</span><span>public</span><span>function</span> getValue2(<span>$param1</span><span>);

    </span><span>//</span><span> 普通方法(非抽象方法)</span><span>public</span><span>function</span><span> getValue0()
    {
        </span><span>return</span> "getValue0"<span>;
    }
}

</span><span>//</span><span> 接口</span><span>interface</span><span> MyInterface1
{
    </span><span>//</span><span> 接口常量,不能被覆盖</span><span>const</span> MyConstant = 'constant value'<span>;
    </span><span>public</span><span>function</span><span> getValue3();
}

</span><span>//</span><span> 接口</span><span>interface</span> MyInterface2 <span>extends</span><span> MyInterface1
{
    </span><span>public</span><span>function</span><span> getValue4();
}

</span><span>//</span><span> 接口</span><span>interface</span><span> MyInterface3
{
    </span><span>public</span><span>function</span><span> getValue5();
}

</span><span>//</span><span> trait(可以 use 多个,允许有实现代码,但是本身不能实例化)</span><span>trait MyTrait1
{
    </span><span>//</span><span> 可以具有方法,静态方法,属性等</span><span>function</span><span> getValue6()
    {
        </span><span>return</span> "getValue6"<span>;
    }
}

</span><span>//</span><span> trait(可以 use 多个,允许有实现代码,但是本身不能实例化)</span><span>trait MyTrait2
{
    </span><span>//</span><span> 抽象方法(use 这个 trait 的类必须要定义这个方法)</span><span>abstract</span><span>function</span><span> getValue7();
}

</span><span>//</span><span> trait(可以 use 多个,允许有实现代码,但是本身不能实例化)</span><span>trait MyTrait3
{
    </span><span>function</span><span> getValue6()
    {
        </span><span>return</span> "getValue6"<span>;
    }

    </span><span>function</span><span> getValue8()
    {
        </span><span>return</span> "getValue8"<span>;
    }
}

</span><span>//</span><span> 必须实现所有抽象方法和接口方法
// 类只能单继承,接口可以多继承</span><span>class</span> MyClass1 <span>extends</span> MyAbstractClass <span>implements</span> MyInterface2,<span> MyInterface3
{
    </span><span>//</span><span> 可以 use 多个 trait</span><span>use</span> MyTrait1,<span> MyTrait2;
    </span><span>use</span><span> MyTrait3
    {
        </span><span>//</span><span> 多 trait 间有重名的,可以指定以哪个为准</span>        MyTrait1::<span>getValue6 insteadof MyTrait3;
        </span><span>//</span><span> 可以为 trait 的指定方法设置别名(调用的时候用方法名也行,用别名也行)</span>        MyTrait3::getValue8 <span>as</span><span> alias;
    }

    </span><span>//</span><span> 可以将 protected 升级为 public</span><span>public</span><span>function</span><span> getValue1()
    {
        </span><span>return</span> "getValue1"<span>;
    }

    </span><span>//</span><span> 可以加参数,但是加的参数必须要有默认值</span><span>public</span><span>function</span> getValue2(<span>$param1</span>, <span>$param2</span> = 'param2'<span>)
    {
        </span><span>return</span> "getValue2, {<span>$param1</span>}, {<span>$param2</span>}"<span>;
    }

    </span><span>public</span><span>function</span><span> getValue3()
    {
        </span><span>return</span> "getValue3"<span>;
    }

    </span><span>public</span><span>function</span><span> getValue4()
    {
        </span><span>return</span> "getValue4"<span>;
    }

    </span><span>public</span><span>function</span><span> getValue5()
    {
        </span><span>return</span> "getValue5"<span>;
    }

    </span><span>public</span><span>function</span><span> getValue7()
    {
        </span><span>return</span> "getValue7"<span>;
    }
}

</span><span>//</span><span> 调用接口常量</span><span>echo</span> MyInterface1::<span>MyConstant;
</span><span>echo</span> "<br>"<span>;

</span><span>$myClass1</span> = <span>new</span><span> MyClass1;
</span><span>echo</span><span>$myClass1</span>-><span>getValue0();
</span><span>echo</span> "<br>"<span>;
</span><span>echo</span><span>$myClass1</span>-><span>getValue1();
</span><span>echo</span> "<br>"<span>;
</span><span>echo</span><span>$myClass1</span>->getValue2("webabcd"<span>);
</span><span>echo</span> "<br>"<span>;
</span><span>echo</span><span>$myClass1</span>-><span>getValue3();
</span><span>echo</span> "<br>"<span>;
</span><span>echo</span><span>$myClass1</span>-><span>getValue4();
</span><span>echo</span> "<br>"<span>;
</span><span>echo</span><span>$myClass1</span>-><span>getValue5();
</span><span>echo</span> "<br>"<span>;
</span><span>echo</span><span>$myClass1</span>-><span>getValue6();
</span><span>echo</span> "<br>"<span>;
</span><span>echo</span><span>$myClass1</span>-><span>getValue7();
</span><span>echo</span> "<br>"<span>;
</span><span>echo</span><span>$myClass1</span>-><span>getValue8();
</span><span>echo</span> "<br>"<span>;
</span><span>echo</span><span>$myClass1</span>-><span>alias();
</span><span>echo</span> "<br>";


OK
[Source code download]

The above has introduced Quick Solution 4 - PHP: Class Basics, Abstract Classes, Interfaces, Traits, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP 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.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

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.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment