happy cat image

everdevel

coding

login
NotificationX
  • Currently, only notices of comments are displayed.
  • no comment or please login

Assigning Rules to Traits

You can specify a method that must be declared in the class that uses the trait.
Same thing with the abstract keyword.

How To Use abstract for trait methods

trait traitname{
    abstract access modifier function method name();
}

So let's look at an example.

<?php
    trait apple
    {
        // must declare likeApple() method
        abstract static function likeApple();

        public static function phone()
        {
            return 'iPhone';
        }
    }

    class disney
    {
        use apple;
    }

    $disney = new disney;
?>

Result

The error occurs because you do not declare the likeApple method in the disney class. The following example declares the likeApple() method.

<?php
    trait apple
    {
        //must declare likeApple() method
        abstract static function likeApple();

        public static function phone()
        {
            return 'iPhone';
        }
    }

    class disney
    {
        use apple;

        public function likeApple()
        {
            return 'Disney and Apple are friendly.';
        }
    }

    $disney = new disney;
    echo $disney->likeApple();
?>

Result

We have seen how to use this abstract to create method rules in a trait. ^-^ *


Thank you for visiting. If you have any inquiry or explanation of mistakes, please use the comments below.


    
    

Back to the course

ALL COMMENTS 0

Sort by