Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instance as a static class property

Tags:

php

static

Is it possible to declare an instance of a class as a property in PHP?

Basically what I want to achieve is:

abstract class ClassA() 
{
  static $property = new ClassB();
}

Well, I know I can't do that, but is there any workaround beside always doing something like this:

if (!isset(ClassA::$property)) ClassA::$property = new ClassB();
like image 411
paudam Avatar asked Feb 06 '12 11:02

paudam


People also ask

Can static class have instance?

Static classes are sealed and therefore cannot be inherited. They cannot inherit from any class except Object. Static classes cannot contain an instance constructor.

Can I create an instance in static method?

Instance method vs Static methodStatic methods can't access instance methods and instance variables directly. They must use reference to object. And static method can't use this keyword as there is no instance for 'this' to refer to.

Can we create instance of static class in Java?

Java allows a class to be defined within another class. These are called Nested Classes. Classes can be static which most developers are aware of, henceforth some classes can be made static in Java. Java supports Static Instance Variables, Static Methods, Static Block, and Static Classes.


2 Answers

you can use a singleton like implementation:

<?php
class ClassA {

    private static $instance;

    public static function getInstance() {

        if (!isset(self::$instance)) {
            self::$instance = new ClassB();
        }

        return self::$instance;
    }
}
?>

then you can reference the instance with:

ClassA::getInstance()->someClassBMethod();
like image 146
Yaron U. Avatar answered Sep 16 '22 23:09

Yaron U.


An alternative solution, a static constructor, is something along the lines of

<?php
abstract class ClassA {
    static $property;
    public static function init() {
        self::$property = new ClassB();
    }
} ClassA::init();
?>

Please note that the class doesn't have to be abstract for this to work.

See also How to initialize static variables and https://stackoverflow.com/a/3313137/118153.

like image 26
Iiridayn Avatar answered Sep 16 '22 23:09

Iiridayn