26

In Jave you can define a public static final variable in a class. Is there an equivalent to this in PHP?

I'd like to do the following:

<?php

class MyClass{

    public final static $finalVariable = "something";
}

MyClass::$finalVariable

and not ever have to worry about $finalVariable changing and not having a new instance for every instantiation of MyClass

Prix
  • 19,417
  • 15
  • 73
  • 132
David
  • 10,418
  • 17
  • 72
  • 122
  • 5
    A *variable* is *variable*. Are you looking for a *constant*? – deceze Aug 16 '13 at 12:59
  • 2
    @deceze - no, final means it can't be overriden in childs, but can be changed (unlike constant) – Alma Do Aug 16 '13 at 13:00
  • Read here: http://stackoverflow.com/questions/2494381/static-classes-in-php-via-abstract-keyword – Massimo De Luisa Aug 16 '13 at 13:02
  • 1
    replace 'public final static' with 'const', and you are good to go. – pinkal vansia Aug 16 '13 at 13:02
  • 1
    @Alma Sure, but the OP said "not ever have to worry about [it] changing". A *variable* can be changed. If he's accessing a static property using `Class::$property`, he never has to worry about *sub classes* because he's explicitly accessing `Class`. – deceze Aug 16 '13 at 13:03
  • this can be implemented as `protected`/`private` field w/ getter w/o setter... – vp_arth Jun 09 '15 at 13:32

2 Answers2

45

From this page in the PHP manual:

Note: Properties cannot be declared final, only classes and methods may be declared as final.

However, you can use class constants as described here.

Your example would look something like this:

<?php

class MyClass{
    const finalVariable = "something";
}

MyClass::finalVariable;
?>

Except of course that finalVariable isn't really an appropriate name because it's not variable =).

Muhammad Hassaan
  • 7,296
  • 6
  • 30
  • 50
brianmearns
  • 9,581
  • 10
  • 52
  • 79
  • 1
    This also doesn't prevent subclasses from overriding it, as one might expect for "final". You can still create a subclass that says "const finalVariable = 99;" and in instances of the subclass it will be 99. – TextGeek Jun 05 '17 at 15:38
4

There is no such thing as final or readonly keywords/concepts for member variables in PHP OOP. final itself is available for classes themselves and functions contained within only.

What you should consider using instead is a class constant, this will guarantee that the value can not change.

class MyClass
{
    const FINALVARIABLE = "something";
}

// Usage
MyClass::FINALVARIABLE
Rudi Visser
  • 21,350
  • 5
  • 71
  • 97