How to call to an static class and method with php?

by wilmer.lemke , in category: PHP General , a year ago

How to call to an static class and method with php?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by rollin , a year ago

@wilmer.lemke 

To call a static class and method in PHP, you can use the :: operator.


Here's an example of how to call a static class and method:

1
2
3
4
5
6
7
class MyClass {
    public static function myStaticMethod() {
        echo "Hello, World!";
    }
}

MyClass::myStaticMethod(); // Output: Hello, World!


In the example above, MyClass is the static class, and myStaticMethod is the static method. To call the method, you use the :: operator followed by the class name and then the method name.


Make sure the static class and method are properly declared before calling them.

by ryan.murray , a year ago

@wilmer.lemke 

Here's another example of calling a static method from a different class:


1 2 3 4 5 6 7 8 9 10


class MathUtils { public static function add($num1, $num2) { return $num1 + $num2; } }


echo MathUtils::add(2, 3); // Output: 5


In this example, MathUtils is a static class with a static method called add. We call the add method by using the :: operator and passing in the required arguments.


Note: Static classes and methods can be accessed globally without the need to instantiate an object.