A PHP trait cannot declare a constant, but is it possible to declare using a DocComment (or otherwise) a constant which the trait might "use" if the class using the trait defines it?
For example, imagine a class Book
is a model bound to the books
table. The framework requires that the table is defined as a TABLE
constant:
class Books extends Model
{
const TABLE = 'books';
}
When creating my model, my IDE autocompletes the TABLE
constant because it's declared on Model
. Wonderful.
Now, say I have a trait called Sluggable
which is a trait which will help the developer manage the book's URL slug (e.g. treasure-island
), and one of the configurations options is whether to automatically sluggify the book's title, or not. Say this is controlled by the AUTOMATIC_SLUGS
constant.
trait Sluggable {
public function generateSlug()
{
if (defined('static::AUTOMATIC_SLUGS') && static::AUTOMATIC_SLUGS) {
// do the thing
}
}
}
Obviously, the trait cannot define the AUTOMATIC_SLUGS
constant because that's not allowed, however the IDE cannot suggest, or otherwise verify the AUTOMATIC_SLUGS
constant. So my model Books
now has a warning on it (in my IDE) telling me that AUTOMATIC_SLUGS
is unused:
class Books extends Model
{
use Sluggable;
const TABLE = 'books';
// IDE complains about this constant
const AUTOMATIC_SLUGS = true;
}
Is there a way for me to – on the trait, and without refactoring to use static properties – declare that Sluggable
will be checking a constant called AUTOMATIC_SLUGS
and have the IDE suggest it/not consider it useless?