Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Is it possible to get the name of the class using the trait from within a trait static method?

Tags:

php

traits

Can the name of a class using a trait be determined from within a static method belonging to that trait?

For example:

trait SomeAbility {
    public static function theClass(){
        return <name of class using the trait>;
    }
}

class SomeThing {
    use SomeAbility;
    ...
}

Get name of class:

$class_name = SomeThing::theClass();

My hunch is, probably not. I haven't been able to find anything that suggests otherwise.

like image 976
user3574603 Avatar asked May 18 '18 08:05

user3574603


People also ask

Can a trait use a trait in PHP?

A trait is similar to a class, but it is only for grouping methods in a fine-grained and consistent way. PHP does not allow you to create an instance of a Trait like an instance of a class. And there is no such concept of an instance of a trait.

How do you name a trait in PHP?

Naming conventions for code released by PHP FIG¶ Interfaces MUST be suffixed by Interface : e.g. Psr\Foo\BarInterface . Abstract classes MUST be prefixed by Abstract : e.g. Psr\Foo\AbstractBar . Traits MUST be suffixed by Trait : e.g. Psr\Foo\BarTrait . PSR-1, 4, and 12 MUST be followed.

What is trait class in PHP?

Traits are used to declare methods that can be used in multiple classes. Traits can have methods and abstract methods that can be used in multiple classes, and the methods can have any access modifier (public, private, or protected).

What is the difference between a class and a trait in PHP?

The main difference between the Traits and Interfaces in PHP is that the Traits define the actual implementation of each method within each class, so many classes implement the same interface but having different behavior, while traits are just chunks of code injected in a class in PHP.


2 Answers

Use late static binding with static:

trait SomeAbility {
    public static function theClass(){
        return static::class;
    }
}

class SomeThing {
    use SomeAbility;
}

class SomeOtherThing {
    use SomeAbility;
}

var_dump(
    SomeThing::theClass(),
    SomeOtherThing::theClass()
);

// string(9) "SomeThing"
// string(14) "SomeOtherThing"

https://3v4l.org/mfKYM

like image 149
Yoshi Avatar answered Oct 05 '22 15:10

Yoshi


Yep, using the get_called_class()

<?php
trait SomeAbility {
    public static function theClass(){
        return get_called_class();
    }
}

class SomeThing {
    use SomeAbility;
}
// Prints "SomeThing"
echo SomeThing::theClass();
like image 37
Jack Skeletron Avatar answered Oct 05 '22 14:10

Jack Skeletron