gpt4 book ai didi

php - 如何使用 php 使用特征内的对象初始化属性?

转载 作者:行者123 更新时间:2023-12-05 06:27:01 25 4
gpt4 key购买 nike

我设置的环境是使用 MAMP 和 php 版本 7.2.14 和 PhpStorm。基于PHP: Trait - Manual ,

traits are mechanisms for code reuse in single inheritance languages...

我创建了一个 ValidationHelper.php 特征来帮助验证表单数据。 Pear 具有类似 email($email_addr) 的验证功能,它接受电子邮件地址进行验证。静态调用此类似乎不再理想,因此我试图实例化它。如果您尝试使用对象初始化属性,Php 会抛出错误,因此,我添加了一个构造函数来实例化该对象。 PHP: Trait - Manual还指出

It is not possible to instantiate a Trait on its own.

On its own 是歧义的关键短语。话虽如此,您将如何添加一个构造函数来初始化某些属性,或使用特征实例化一个对象?

Can Traits have properties...Constructors是我读到特征可以有这些成员的地方。我确实看到他们包含一个构造函数,但不能 100% 确定它是如何工作的。

include_once 'Pear/Validate.php';
trait ValidationHelper
{

protected $validate;

public function __constructor(){
$this->validate = new Validate();
}

public function validate_email($email){
return $this->validate->email($email); //$validate is null
}

}

最佳答案

@凯文维金斯

好像有误会。如Can Traits have properties...Constructors的第一个答案中所述

Traits can have a constructor and destructor but they are not for the trait itself, they are for the class which uses the trait. Therefore I wouldn't recommend to do this.

这意味着如果您在包含的特征中声明构造函数/析构函数,则此函数的作用就好像它是在类本身中声明的一样。所以这只有在特征中定义了添加到类中的唯一类变量时才有效。

一个特征本身根本不能被实例化。它只是注入(inject)到一个类中的一组代码,因此其行为与在该类本身中编写的一样。

关于php - 如何使用 php 使用特征内的对象初始化属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55675544/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com