Phpinspectionsea: Self referencing: __CLASS__/self::class in traits

Created on 20 Aug 2017  路  2Comments  路  Source: kalessil/phpinspectionsea

PHP | Php Inspections (EA Extended) | Code Style | Self class referencing

Maybe in this case you like to refer really to trait class reference, and not the __CLASS__ (that here will works like static::class).

bug / false-positive fixed

Most helpful comment

Oh, sure... On my case I am working with the Cache from Laravel, and it requires a key name. In my case, I need that my trait works with a single key, so I have implemented like:

trait CacheGlobally {
    public function cache($object) {
        Cache::put(self::class, $object);
    }
}

But the problem here is that self::class will refer to class that uses this trait, and not the trait itself (that is what I need). So the correct approach should be:

trait CacheGlobally {
    public function cache($object) {
        // Replace self::class by CacheGlobally::class (the trait reference)
        Cache::put(CacheGlobally::class, $object);
    }
}

But it will trigger the inspection telling that I should replace it with self::class, which will change the behaviour here.

All 2 comments

I'm not sure what do you mean. Considering https://3v4l.org/7SDdY, can you provide an example of the false-positive, please?

Oh, sure... On my case I am working with the Cache from Laravel, and it requires a key name. In my case, I need that my trait works with a single key, so I have implemented like:

trait CacheGlobally {
    public function cache($object) {
        Cache::put(self::class, $object);
    }
}

But the problem here is that self::class will refer to class that uses this trait, and not the trait itself (that is what I need). So the correct approach should be:

trait CacheGlobally {
    public function cache($object) {
        // Replace self::class by CacheGlobally::class (the trait reference)
        Cache::put(CacheGlobally::class, $object);
    }
}

But it will trigger the inspection telling that I should replace it with self::class, which will change the behaviour here.

Was this page helpful?
0 / 5 - 0 ratings