happy cat image

Start Web Coding

Your First step toward web coding,
Start Web Coding

change UI

Calling methods in a trait without instantiation

Did you call a method of a class without instantiating it using the static keyword?
Yes, this is possible if the trait's methods also use static, which is called method static invocation.

How to use static in a trait method

trait traitname{
    access modifier static function method name(){}
}

So let's look at an example.

<?php
    trait apple
    {
        public static function phone()
        {
            return 'iPhone';
        }
    }

    class people
    {
        use apple;
    }

    echo "Judith in zootopia ".people::phone()." Use it.";
?>

Result

Traits can also set rules. The rules you declared in the trait must be declared in the class.
See you next time.

강좌로 돌아가기