简体   繁体   中英

How does Laravel dynamically call a class method statically without implicitly using the static keyword for the method in PHP?

Laravel makes it possible to call a class method using the scope resolution operator (::) without the method being statically declared.

In PHP you can only call static methods only when they are declared as such, for example:

class User {

   public static function getAge() { ... } 

}

Can be called as User::getAge();

How can this be done in a normal PHP class. I guess for it to be possible it needs to be done using a design pattern or something else. Can anyone help me out?

So what I meant by the above was is it possible to instantiate a class and call it's method statically in php. Since that feature was dropped from previous versions

class Student {

     public function examScore($mark_one, $mark_two) {
         //some code here
     }

}

How do access it in this manner

$student = new Student;
$student::examScore(20, 40);

And I talked about Laravel because it allows you to alias your classes and call it in this manner Student::examScore(20,40);

Something called facade pattern or so. An explanation with example can help.

After a long search I found an article that kind of explains it here:

https://www.sitepoint.com/how-laravel-facades-work-and-how-to-use-them-elsewhere

My guess here is that your User class actually extends the Laravel Model class.

This class implements some of PHPs so called magic methods. You can find our about them here: https://www.php.net/manual/en/language.oop5.magic.php

One of these is __callStatic .

In Model.php :

/**
 * Handle dynamic static method calls into the method.
 *
 * @param  string  $method
 * @param  array  $parameters
 * @return mixed
 */
public static function __callStatic($method, $parameters)
{
    return (new static)->$method(...$parameters);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM