1

its possible to have static variables for traits:

Trait Example
{
    public static $var;
}

class X
{
    use Example;
}

class Y
{
    use Example;
}

however, the problem is when more class would want to use this trait, I get a fatal error:

Example and X define the same property ($var) in the composition of Y. This might be incompatible, to improve maintainability consider using accessor methods in traits instead. Class was composed

how to define this static variable just for the trait itself?

1 Answer 1

4

Traits can define both static members and static methods. however You can not reassign trait properties.

From PHP manual http://php.net/traits

See Example #12 Conflict Resolution

If a trait defines a property then a class can not define a property with the same name, otherwise an error is issued. It is an E_STRICT if the class definition is compatible (same visibility and initial value) or fatal error otherwise.

The solution would be to override properties in the class

 Trait Example
{
    public static $var;
}

class X
{
    use Example;
    public static $var;
}

class Y
{
    use Example;
    public static $var;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Which version of php?
php 8.0 threw the error. php 8.1 - 8.3 don't have the issue

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.