0

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
4
  • Can you provide an example of such a method in Laravel and how you would call it to make it clear what you are referring to? Commented Mar 2, 2020 at 9:11
  • An example is how the Blade class is used to call its methods example Blade::compileString($param) Commented Mar 2, 2020 at 15:33
  • 1
    This first two videos here would also be of interest to you. Commented Mar 3, 2020 at 11:11
  • Thanks Delena the videos really helped. Commented Mar 4, 2020 at 7:48

1 Answer 1

2

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

No I am not using Laravel Model. I want to know how it can be done in raw PHP. Can you help with a little real world example please
@ A.L. this answer has been very helpful but I what I was looking for is explained here : sitepoint.com/… thanks so much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.