3

I've been looking if there exists something like a static initializer in PHP.

Here is a static method as a Java example:

public class Foo {
    static {  //This is what I mean (Does this exist in other languages like PHP?
       //THIS IN PHP
    }
}

I found what it's name (static initializer). It is used the first time the Class its loaded. Seems like theres not static initializer in PHP.

3
  • 4
    yes, there's static methods in php, and no, that's no php - that's java. and no, there's no static "blocks" in php. methods can be static, class attributes (aka class vars) can be static, but not blocks of code. classes cannot contain bare code. Commented Jan 13, 2016 at 21:10
  • Those are not static methods, but static variables... Commented Jan 13, 2016 at 21:12
  • @MarcB you should make your comment an answer, because that's what it is Commented Jan 13, 2016 at 21:17

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yep, thats right. Finally i decided to use public static function init(){ Class::Foo = new Foo(); } That's the way i did it, the only problem i have to call init() but well. :·) Thanks alot.
-1

Static properties and methods in PHP

class SomeClass {
    private static $property = 'Foo';

    public static function getProperty() {
        return self::$property;
    }
}

SomeClass::getProperty();

Non static properties and methods

class SomeClass {
    private $property = 'Foo';

    public function getProperty() {
        return $this->property;
    }
}

$class = new SomeClass();
$class->getProperty();

1 Comment

This is NOT a static block(initializer), it is only a method as static.

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.