Home Backend Development PHP Tutorial Quick Fix 4 - PHP: Class Basics, Abstract Classes, Interfaces, Traits

Quick Fix 4 - PHP: Class Basics, Abstract Classes, Interfaces, Traits

Jul 29, 2016 am 08:51 AM
echo gt return

[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> 类常量,没有&ldquo;$&rdquo;符号,不能被覆盖</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 />";
Copy after login


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 />";
Copy after login


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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the differences between Huawei GT3 Pro and GT4? What are the differences between Huawei GT3 Pro and GT4? Dec 29, 2023 pm 02:27 PM

Many users will choose the Huawei brand when choosing smart watches. Among them, Huawei GT3pro and GT4 are very popular choices. Many users are curious about the difference between Huawei GT3pro and GT4. Let’s introduce the two to you. . What are the differences between Huawei GT3pro and GT4? 1. Appearance GT4: 46mm and 41mm, the material is glass mirror + stainless steel body + high-resolution fiber back shell. GT3pro: 46.6mm and 42.9mm, the material is sapphire glass + titanium body/ceramic body + ceramic back shell 2. Healthy GT4: Using the latest Huawei Truseen5.5+ algorithm, the results will be more accurate. GT3pro: Added ECG electrocardiogram and blood vessel and safety

Detailed explanation of the usage of return in C language Detailed explanation of the usage of return in C language Oct 07, 2023 am 10:58 AM

The usage of return in C language is: 1. For functions whose return value type is void, you can use the return statement to end the execution of the function early; 2. For functions whose return value type is not void, the function of the return statement is to end the execution of the function. The result is returned to the caller; 3. End the execution of the function early. Inside the function, we can use the return statement to end the execution of the function early, even if the function does not return a value.

Fix: Snipping tool not working in Windows 11 Fix: Snipping tool not working in Windows 11 Aug 24, 2023 am 09:48 AM

Why Snipping Tool Not Working on Windows 11 Understanding the root cause of the problem can help find the right solution. Here are the top reasons why the Snipping Tool might not be working properly: Focus Assistant is On: This prevents the Snipping Tool from opening. Corrupted application: If the snipping tool crashes on launch, it might be corrupted. Outdated graphics drivers: Incompatible drivers may interfere with the snipping tool. Interference from other applications: Other running applications may conflict with the Snipping Tool. Certificate has expired: An error during the upgrade process may cause this issu simple solution. These are suitable for most users and do not require any special technical knowledge. 1. Update Windows and Microsoft Store apps

What is the execution order of return and finally statements in Java? What is the execution order of return and finally statements in Java? Apr 25, 2023 pm 07:55 PM

Source code: publicclassReturnFinallyDemo{publicstaticvoidmain(String[]args){System.out.println(case1());}publicstaticintcase1(){intx;try{x=1;returnx;}finally{x=3;}}}#Output The output of the above code can simply conclude: return is executed before finally. Let's take a look at what happens at the bytecode level. The following intercepts part of the bytecode of the case1 method, and compares the source code to annotate the meaning of each instruction in

Five selected Go language open source projects to take you to explore the technology world Five selected Go language open source projects to take you to explore the technology world Jan 30, 2024 am 09:08 AM

In today's era of rapid technological development, programming languages ​​are springing up like mushrooms after a rain. One of the languages ​​that has attracted much attention is the Go language, which is loved by many developers for its simplicity, efficiency, concurrency safety and other features. The Go language is known for its strong ecosystem with many excellent open source projects. This article will introduce five selected Go language open source projects and lead readers to explore the world of Go language open source projects. KubernetesKubernetes is an open source container orchestration engine for automated

Laravel development: How to implement WebSockets communication using Laravel Echo and Pusher? Laravel development: How to implement WebSockets communication using Laravel Echo and Pusher? Jun 13, 2023 pm 05:01 PM

Laravel is a popular PHP framework that is highly scalable and efficient. It provides many powerful tools and libraries that allow developers to quickly build high-quality web applications. Among them, LaravelEcho and Pusher are two very important tools through which WebSockets communication can be easily implemented. This article will detail how to use these two tools in Laravel applications. What are WebSockets? WebSockets

Go language development essentials: 5 popular framework recommendations Go language development essentials: 5 popular framework recommendations Mar 24, 2024 pm 01:15 PM

&quot;Go Language Development Essentials: 5 Popular Framework Recommendations&quot; As a fast and efficient programming language, Go language is favored by more and more developers. In order to improve development efficiency and optimize code structure, many developers choose to use frameworks to quickly build applications. In the world of Go language, there are many excellent frameworks to choose from. This article will introduce 5 popular Go language frameworks and provide specific code examples to help readers better understand and use these frameworks. 1.GinGin is a lightweight web framework with fast

Detailed explanation of the role and usage of the echo keyword in PHP Detailed explanation of the role and usage of the echo keyword in PHP Jun 28, 2023 pm 08:12 PM

Detailed explanation of the role and usage of the echo keyword in PHP PHP is a widely used server-side scripting language, which is widely used in web development. The echo keyword is a method used to output content in PHP. This article will introduce in detail the function and use of the echo keyword. Function: The main function of the echo keyword is to output content to the browser. In web development, we need to dynamically present data to the front-end page. At this time, we can use the echo keyword to output the data to the page. e

See all articles