Welcome Guest, Not a member yet? Register   Sign In
Using ::class in Model's $returnType instead of string - bad?
#1

Before I go abound and create a PR for a documentation change, I have to ask if I have misunderstood something.
I am refactoring my CI 4.1.9 project in PHPstorm and found out that
PHP Code:
protected $returnType App\Entities\SomeEntity::class; 
 is an excellent way of writing this instead of specifying this as a string 
PHP Code:
protected $returnType 'App\Entities\SomeEntity'

As I read it from the documentation, "::class" expands at compile time so it can't be for performance reasons - https://www.php.net/manual/en/language.oop5.basic.php
What am I missing?
/Mattias
Reply
#2

Yes, "::class" is better.
If you are using an IDE, the IDE auto completes class names to avoid typos,
and you can go to the class file with one click.
Reply
#3

Actually, the Model Generator creates the return types using the "::class" syntax:
PHP Code:
$return '\\' trim($return'\\') . '::class';
$this->call('make:entity'array_merge([$baseClass], $this->params)); 

See https://github.com/codeigniter4/CodeIgni...#L126-L127
Reply
#4

So maybe then the docs should be updated to reflect "best practices"?
Reply
#5

(06-15-2022, 11:12 PM)tgix Wrote: So maybe then the docs should be updated to reflect "best practices"?

Yes.
Reply
#6

(This post was last modified: 06-16-2022, 02:34 AM by tgix.)

(06-16-2022, 02:12 AM)kenjis Wrote:
(06-15-2022, 11:12 PM)tgix Wrote: So maybe then the docs should be updated to reflect "best practices"?

Yes.

Working on a PR.

https://github.com/codeigniter4/CodeIgniter4/pull/6134
Reply
#7

Thanks for the discussion and contribution! I use ::class any time I have a class string. You can also use the special phpdoc block type `class-string` to narrow types for IDE and static analysis (e.g. https://phpstan.org/writing-php-code/php...ass-string)
Reply
#8

(06-16-2022, 04:35 AM)MGatner Wrote: Thanks for the discussion and contribution! I use ::class any time I have a class string. You can also use the special phpdoc block type `class-string` to narrow types for IDE and static analysis (e.g. https://phpstan.org/writing-php-code/php...ass-string)

Cool. phpstan is next on my to-do-list to start using.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB