How to Create Static Classes in PHP (Like in C#)

Is it possible to create static classes in PHP (like in C#)?

You can have static classes in PHP but they don't call the constructor automatically (if you try and call self::__construct() you'll get an error).

Therefore you'd have to create an initialize() function and call it in each method:

<?php

class Hello
{
private static $greeting = 'Hello';
private static $initialized = false;

private static function initialize()
{
if (self::$initialized)
return;

self::$greeting .= ' There!';
self::$initialized = true;
}

public static function greet()
{
self::initialize();
echo self::$greeting;
}
}

Hello::greet(); // Hello There!

?>

Static initializer or static constructor in PHP?

I don't think PHP provides any direct ways to initialize classes like it's done in Java or C#. If you want to initialize static class members you can do it within a constructor, something like this:

class MyClass {

private static $staticValue;

public function __construct() {
if (self::$staticValue === null){
self::$staticValue = 'Nice';
}
}
}

However, the above approach won't work if you never instantiate your class. That means that accessing static class members won't trigger the code in __construct unfortunately, and I don't think there's any workaround for this problem in PHP.

What are the desirable situation (real life example) to create static methods except for creating helper?

A static method makes sense when there’s no state to maintain. What do I mean by state? Well, consider the following: You have two distinct objects, a and b, which are both of type EmployeeBal. Is there ever a case in your program where a.GetAllEmployees() and b.GetAllEmployees() would yield different results?

If not, then why do the objects a and b exist at all? The whole point of having objects is to associate some distinct state with them. If two different objects can never refer to a different state, then they fulfil no purpose.

In fact, in this situation your EmployeeBal would be exactly equivalent to System.Math, and all its methods are “helper methods” (if that’s what you want to call them). In this case, forget about static methods for a minute: your whole class should be static (static class EmployeeBal), and it should not have any constructors; because the concept of an object of type EmployeeBal simply makes no sense. In fact, in other languages EmployeeBal wouldn’t be a class at all; instead, it would be something generally called a module: a unit that logically groups code. C# has no modules, and all code must reside within classes. Classes thus fulfil a dual purpose: they group code, and they generate objects.1

Now consider a less extreme case: EmployeeBal objects actually maintain state, and differ. Yet GetAllEmployees() will still yield the same result, regardless of which object calls the method.

In this case, EmployeeBal obviously cannot be a static class. But GetAllEmployees is still stateless, and thus doesn’t belong to objects of type EmployeeBal. And thus the method should be static.


1 This lack of distinction between two fundamentally distinct concepts (module and class) is actually quite annoying, and the main reason that C# behaves this way is because it was conceived to be similar to Java. It was a mistake in hindsight, but not a serious one.

Is there an equivalent to $this for static classes? ( kind of super but for the current class where it is used )

self::method();

Cant get static variable from $class

If you don't have PHP version of 5.3 and above, and you don't want to use reflection (which in my opinion is an overkill - unless you want to access multiple static properties) you can define getter function and call it via call_user_func():

class A {
public static $var = "Hello";
public static function getVar() {
return self::$var;
}
}
$className = "A";
echo call_user_func(array($className, 'getVar'));

Two different class librarys sharing one static class library

...one script is changing the values inside the static library class of the other one

Given this is the same static class, shared across multiple libraries, then the behaviour you describe is correct. When you make something static that means that it belongs to a type rather than a specific object so changing it means everything within the same app domain that references/uses it will see those changes.

Static and Instance methods with the same name?

No you can't. The reason for the limitation is that static methods can also be called from non-static contexts without needing to prepend the class name (so MyStaticMethod() instead of MyClass.MyStaticMethod()). The compiler can't tell which you're looking for if you have both.

You can have static and non-static methods with the same name, but different parameters following the same rules as method overloading, they just can't have exactly the same signature.



Related Topics



Leave a reply



Submit