Kevin Wiggins
Kevin Wiggins

Reputation: 544

How to initialize a property with an object within side a trait using php?

The environment I have set up is using MAMP with php version 7.2.14 and PhpStorm. Based on the PHP: Trait - Manual,

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

I have created a ValidationHelper.php trait to help validate form data. Pear has validation functionality like email($email_addr) that accepts an email address to validate. Calling this class statically appears to no longer be ideal, so I am attempting to instantiate it. Php throws an error if you attempt to initialize a property with an object, therefore, I added a constructor to instantiate the object. The PHP: Trait - Manual also states that

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

On its own being the key phrase for ambiguity. With that being said, how would you add a constructor that initializes some property, or instantiate an object using a trait?

Can Traits have properties...Constructors is where I read that traits can have these members. I do see that they included a constructor, but not 100% sure how it works.

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
    }

}

Upvotes: 3

Views: 2745

Answers (2)

Alexander Behling
Alexander Behling

Reputation: 627

@Kevin Wiggins

It seems that there is a misunderstanding. As mentioned in the first answer of 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.

This means that if you declare a constructor / destructor in the included trait this function acts as if it was declare in the class itself. So this will only work, if the only class vars added to the class are defined in the trait.

A trait itself can not be instantiate at all. It is only a grouped piece of code which is injected in a class and therefore behave as it was written in this class itself.

Upvotes: 2

Kevin Wiggins
Kevin Wiggins

Reputation: 544

Instead of trying to instantiate an object within a trait, instantiate it within your hierarchal system.

include_once 'Pear/Validate.php';
class My_Object_Class
{
    protected $validate;
    public function __construct(){
        $this->validate = new Validate();
    }
}

Upvotes: -1

Related Questions