Re: [RFC] Allow ::class on objects
| From: | Kalle Sommer Nielsen | Date: | Thu, 09 Jan 2020 21:02:31 +0000 |
| Subject: | Re: [RFC] Allow ::class on objects | ||
| References: | 1 2 3 4 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-108078@lists.php.net to get a copy of this message | ||
Moi
Den tor. 9. jan. 2020 kl. 22.41 skrev Mike Schinkel <mike@newclarity.net>:
>
> > On Jan 9, 2020, at 3:29 PM, Ralph Schindler <ralph@ralphschindler.com> wrote:How
> > would you get the right semantics out of $object::interface, or $object::trait, and/or do you have
> > an example of what you're expecting?
>
> Sorry, I was only thinking about using it on Interface and Trait names, not on objects.
Traits are compiler assisted code copy/paste and not contracts (unlike
interfaces), so there is no gain in having ::trait.
> I have a lot of code that looks like this:
>
> use Interfaces;
> if ( ! implements_interface( $object, Interfaces\MyInterface::class, $trigger_error = true )) {
> return;
> }
>
> And it feels wrong. I would love to be able to use ::interface, i.e.:
>
> use Interfaces;
> if ( implements_interface( $object, Interfaces\MyInterface::interface, $trigger_error = true ))
> {
> return;
> }
If your $object variable is an actual instance, you can use the
instanceof operator, it treats the right operand as a first class
citizen and allows you to skip writing ::class:
use Interfaces;
if(!$object instanceof Interfaces\MyInterface)
{
// Notice the ! is right associative and instanceof is non
associative, hence the lack of parantheses
}
use Interfaces;
if($object instanceof Interfaces\MyInterface)
{
}
--
regards,
Kalle Sommer Nielsen
kalle@php.net