Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static methods in PHP

Why in PHP you can access static method via instance of some class but not only via type name?

UPDATE: I'm .net developer but i work with php developers too. Recently i've found this moment about static methods called from instance and can't understand why it can be usefull.

EXAMPLE:

class Foo {     public static Bar()     {     } } 

We can accept method like this:

var $foo = new Foo(); $foo.Bar(); // ?????? 
like image 819
donRumatta Avatar asked Feb 09 '12 07:02

donRumatta


People also ask

What is static method PHP?

The static keyword is used to declare properties and methods of a class as static. Static properties and methods can be used without creating an instance of the class. The static keyword is also used to declare variables in a function which keep their value after the function has ended.

When use static methods PHP?

When you use static, this is to call a function without an instance of the class. The main reason is often to represent a service class which should not be instantiated many times. A static class (with only static functions) prevent you from using many OOP features like inheritance, interface implementation.

What is a static method?

A static method (or static function) is a method defined as a member of an object but is accessible directly from an API object's constructor, rather than from an object instance created via the constructor.

What is static method with example?

A static method in Java is a method that is part of a class rather than an instance of that class. Every instance of a class has access to the method. Static methods have access to class variables (static variables) without using the class's object (instance).


1 Answers

In PHP

the class is instantiated using the new keyword for example;

$MyClass = new MyClass();

and the static method or properties can be accessed by using either scope resolution operator or object reference operator. For example, if the class MyClass contains the static method Foo() then you can access it by either way.

$MyClass->Foo(); 

Or

MyClass::Foo() 

The only rule is that static methods or properties are out of object context. For example, you cannot use $this inside of a static method.

like image 143
Ibrahim Azhar Armar Avatar answered Sep 18 '22 23:09

Ibrahim Azhar Armar