G
G
Gramcoder2020-02-11 19:14:06
PHP
Gramcoder, 2020-02-11 19:14:06

How to get default class properties?

How can I get the default properties of a class?

What is the point.
There is a class Handler, in it the search and launch of the desired class-command takes place. Each command class has a property protected $namethat specifies the name of this command. Actually by name, identification and launch occurs. All command classes inherit one common class Commandwith basic methods. There are many of these command classes. And so the question arose, what is the best way to do this kind of search?

class StartCommand extends Command
{
    protected $name = 'start';

    public function handle()
    {
        //
    }
}


One solution is to add a method getNameto the parent class Commandand get the value of the property like so:

$commands = [
    \StartCommand::class
];

$names = [];
foreach($commands as $commandClassName) {
    $name[] = (new $commandClassName)->getName();
}


Another solution is to specify the name as a static property:

$name[] = $commandClassName::getName();
    // или
    $name[] = (new $commandClassName::$name;


And let's say there are about 100 such classes, what is the best way to get the property value for performance?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Shamanov, 2020-02-11
@SilenceOfWinter

classReflectionProperty

D
Dmitry Chekanov, 2020-02-11
@LanDer931

Static method but without creating an object, as is done in your example.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question