Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a final variable in PHP?

Tags:

php

final

php-7

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 !
like image 882
vdegenne Avatar asked Dec 29 '16 14:12

vdegenne


2 Answers

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

like image 142
Machavity Avatar answered Sep 24 '22 19:09

Machavity


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;
like image 31
Acuna Avatar answered Sep 21 '22 19:09

Acuna