How do you declare a final variable in php?

I can't find out, or maybe I am thinking wrongly but I need to make a variable that can't be changed, like read-only, something like :

final $finalVar = 'extremely secret number'; // don't change

$finalVar = 'hacked...'; // THROW I GIANT BIG ERROR HERE !

asked Dec 29, 2016 at 14:16

How do you declare a final variable in php?

vdegennevdegenne

10.8k14 gold badges75 silver badges101 bronze badges

9

Aside from constants (as mentioned in comments), the only way I can think of to do this is to use a parent-child relationship with a private variable

class ParentC {
    private $var = 'bob';
}

class ChildC extends ParentC {
    public function setVar() {
         // Fatal error: Uncaught Error: Cannot access private property ParentC::$var
         echo parent::$var; 
    }
}

Note that there's a hacky way around that using the Reflection class. But, for the most part, you can't touch a private parent variable from a child class

answered Dec 29, 2016 at 14:36

How do you declare a final variable in php?

MachavityMachavity

30.1k26 gold badges87 silver badges98 bronze badges

2

You can use constants if you want to create variables which you don't want to be changed:

class MyClass {

   const VERSION = '2.1'; // This constant can be view outside the class,
                          // but its value can't be changed even in this class

   function myMethod () {
       echo self::VERSION; // Inside class
   }

}

or outside the class:

echo MyClass::VERSION;

Functional approach:

define ('VERSION', '2.1');

echo VERSION;

answered Aug 3, 2019 at 15:03

AcunaAcuna

1,58715 silver badges19 bronze badges

While there has been talk of read-only variables since at least 2012, with even an RFC proposing it on objects, the support does not exist in the language.

One way to achieve a read-only variable (or a collection of read-only variables, as might be important with certain configuration values) is with a mediating container:

class Readonly {
    public function __construct(...$vars) {
        $this->vars;
    }

    public function __set($var, $value) {
        if (array_key_exists($var, $this->vars)) {
            throw new \LogicException("Variable $var is read-only");
        } else {
            $this->vars[$var] = $value;
        }
    }

    public function __get($var) {
        return array_key_exists($var, $this->vars) ? $this->vars[$var] : null;
    }

    protected $vars = [];
}

Which allows you to create a container of read-only variables:

$config = new Readonly('apikey');

$config->apikey = 'A01AB020'; // this works, first time set
echo $config->apikey;

$config->apikey = '00000000'; // boom! it's "final"

answered Dec 29, 2016 at 14:40

How do you declare a final variable in php?

bishopbishop

35.4k10 gold badges99 silver badges133 bronze badges

3

Use constant:

defined('VARIABLE')  OR define('VARIABLE', 'value');

Documentation: define defined

Blaztix

1,1651 gold badge18 silver badges28 bronze badges

answered Feb 19, 2019 at 11:43

How do you declare a final variable in php?

0

With PHP 8.1 you can now declare a variable as readonly :

class MyClass{
    public readonly string $prop;
 
    public function __construct(string $val) {
        // Can be intialized only once.
        $this->prop = $val;
    }
}

$myclass = new MyClass('Foo');
$myclass->prop; // Read the property
$myclass->prop = 'Bar'; // Error: Cannot modify readonly property

Note that you can only apply readonly to typed properties.

answered Nov 26, 2021 at 9:50

grunkgrunk

14.3k14 gold badges65 silver badges107 bronze badges

Not the answer you're looking for? Browse other questions tagged php final php-7 or ask your own question.

What is final variable PHP?

The final keyword is used to prevent a class from being inherited and to prevent inherited method from being overridden.

How do you declare a final variable?

There are three ways to initialize a final variable:.
You can initialize a final variable when it is declared. This approach is the most common. ... .
A blank final variable can be initialized inside an instance-initializer block or inside the constructor. ... .
A blank final static variable can be initialized inside a static block..

How a variable is declared in PHP?

A variable starts with the $ sign, followed by the name of the variable. A variable name must start with a letter or the underscore character. A variable name cannot start with a number. A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )

How do you call a final class method in PHP?

The final keyword prevents child classes from overriding a method or constant by prefixing the definition with final . If the class itself is being defined final then it cannot be extended. Note: Properties cannot be declared final: only classes, methods, and constants (as of PHP 8.1. 0) may be declared as final.