CLASS web

PHP

trait static

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.";
?>

I'll check the results right below.







Result

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





ALL COMMENTS 0

Sort by

PinkCoding

PinkCoding

X

PinkCoding

Web Scratch Pad

X

loading

            
            
        

Back to the course