search
HomeBackend DevelopmentPHP Tutorial用Trait来导入Util函数能否作为一种解决方法?

一般对于Util方法,不外乎下面几种方法,以及我的一点看法:

  • 依赖注入(好,但麻烦,且Util似乎与注入对象的主业关系不大)
  • 弄一个包含Util方法的Container,然后注入(比上面那个只好一点点)
  • 静态方法(static is evil)

PHP 5.4 引入了 Trait,一般来说,用它作为 Interface 的默认实现似乎受众比较多。

用 Trait 来导入 Util 函数肯定是可行的,但这种解决方法是否违背 OOP 原则?是否最佳或者“优雅”呢?我举个例子:

<code>Trait FormatDatetimeTrait
{
    proteted function formatDatetime($datetime, $style)
    {
        return date($style, $datetime);
    }
}
</code>

好了,这个方法干的活儿似乎多余————这不是我们讨论的重点,这只是个例子。在其他类中使用这个 Trait:

<code>Class FooBar
{
    use FormatDatetimeTrait;

    /** Other stuff **/
    protected function getDate()
    {
        return $this->formatDatetime($this->time, $this->timeStyle);
    }
}
</code>

我想这里 Trait 的引用还是有好处的:

  • 依赖关系明了,虽然和类的主业关系不大,但毕竟用到它了
  • 导入的方法可以改名(formatDatetime as formatTime)
  • 客户类可以在导入函数基础之上扩展

那么,作为一种代码重用的工具,这么使用 Trait 都有那些缺点呢?是否违背 OOP 原则,或者违背它的设计初衷呢?

也欢迎有其他语言 Trait 使用经验的朋友提出宝贵意见 :-)。

回复内容:

一般对于Util方法,不外乎下面几种方法,以及我的一点看法:

  • 依赖注入(好,但麻烦,且Util似乎与注入对象的主业关系不大)
  • 弄一个包含Util方法的Container,然后注入(比上面那个只好一点点)
  • 静态方法(static is evil)

PHP 5.4 引入了 Trait,一般来说,用它作为 Interface 的默认实现似乎受众比较多。

用 Trait 来导入 Util 函数肯定是可行的,但这种解决方法是否违背 OOP 原则?是否最佳或者“优雅”呢?我举个例子:

<code>Trait FormatDatetimeTrait
{
    proteted function formatDatetime($datetime, $style)
    {
        return date($style, $datetime);
    }
}
</code>

好了,这个方法干的活儿似乎多余————这不是我们讨论的重点,这只是个例子。在其他类中使用这个 Trait:

<code>Class FooBar
{
    use FormatDatetimeTrait;

    /** Other stuff **/
    protected function getDate()
    {
        return $this->formatDatetime($this->time, $this->timeStyle);
    }
}
</code>

我想这里 Trait 的引用还是有好处的:

  • 依赖关系明了,虽然和类的主业关系不大,但毕竟用到它了
  • 导入的方法可以改名(formatDatetime as formatTime)
  • 客户类可以在导入函数基础之上扩展

那么,作为一种代码重用的工具,这么使用 Trait 都有那些缺点呢?是否违背 OOP 原则,或者违背它的设计初衷呢?

也欢迎有其他语言 Trait 使用经验的朋友提出宝贵意见 :-)。

Trait 属于静态模板(虽然可以被使用的类改写),不具备继承特性,所以不能用于继承关系比较复杂的场景。比如:

<code>有一个 BaseTrait,被两个 UtilTraitA, UtilTraitB 都 use 了,然后呢,在一个类里面,要同时用到这两个 UtilTrait,这时问题来了,由于他们两个都使用同一个BaseTrait,BaseTrait 里面的方法就被重复导入了,这种冲突直接报错,并且无法解决。
</code>

Trait 的设计就是语法糖,具备类似继承的特征,但是和继承不一样。

所以,Util 方法全部改写为 Trait 虽然一开始可行,但必定会遇到使用时的冲突,因为如果使用了 Util Trait,其他 User Trait 再使用 Util Trait,那么使用这些 User Trait 的类极易产生导入冲突。

那么,Trait 应该怎么用?当模版用!解决少量代码重复的语法糖。绝对不可以把它用作继承体系的一部分,并且要注意方法命名,尽量避免和其他类产生冲突。

最后,Trait 不可以 implement interface,PHP 这么设计还是有道理的。

原讨论: https://coding.net/u/fwolf/pp/25934

楼主,对于Trait的用途php官方文档说的很详细,你应该再仔细读读。

自 PHP 5.4.0 起,PHP 实现了代码复用的一个方法,称为 traits。
Traits 是一种为类似 PHP 的单继承语言而准备的代码复用机制。Trait 为了减少单继承语言的限制,使开发人员能够自由地在不同层次结构内独立的类中复用方法集。Traits 和类组合的语义是定义了一种方式来减少复杂性,避免传统多继承和混入类(Mixin)相关的典型问题。
Trait 和一个类相似,但仅仅旨在用细粒度和一致的方式来组合功能。Trait 不能通过它自身来实例化。它为传统继承增加了水平特性的组合;也就是说,应用类的成员不需要继承。

http://php.net/manual/zh/language.oop5.traits.php

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

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