Is it possible to define a local constant inside a PHP function?

It might be nice to define a local constant within the scope of a function in PHP.

Thus, anyone who reads this function will know that this definition is final in the function and does not affect external code.

Something like this (Invalid syntax):

public function laughManiacally($count){ const LAUGH = 'HA'; for($i=0;$i<$count;$i++){ echo LAUGH; } }; 

Or perhaps (again invalid):

 ... final $laugh = 'HA'; ... 

Is there anyway to do this? And if not, then why?

+5
source share
3 answers

You must have

 echo name_of_class::LAUGH 

Otherwise, PHP will look for a global constant created using define() .


Followup:

You can also define constants only at the object level, for example

 class foo { const BAR = 'baz'; // valid function foo() { const BAR = 'baz'; // invalid. can't define constants INSIDE a method. } } 
+6
source

No, in PHP there are no function level constants. The closest thing is the class constant :

 class A { const LAUGH = 'HA'; function laughManiacally($count) { for ($i=0; $i < $count; ++$i) { echo static::LAUGH; } } } $obj = new A(); $obj->laughManiacally(5); 

Output:

 HAHAHAHAHA 

I also tried final $laugh = 'HA';

final cannot be applied to class properties - only to methods.

I would suggest reading the documentation instead of blind random syntax ..

+3
source

I think you confuse const with the scope here.

 function foo() { $x = 1; } 

I do not need to declare $x as const , because it is already bound to foo() . I would have to explicitly raise it to a global scale in order to use it elsewhere (which is a bad idea for many reasons ). $x can be changed, but only if you do it in your function or edit the code.

Ironically, the constants set using define are globally limited, and const usually global if you use the autoloader

+1
source

Source: https://habr.com/ru/post/1257650/


All Articles