Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

This way anyone reading the function would know that that definition is final within the function and doesn't affect any external code

Something like this (Not valid syntax):

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

Or possibly (Again not valid):

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

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

UPDATE

The way that JavaScript allows block level constant declaration is similar to the functionality I was searching for

function laughManiacally(count) {   const LAUGH = 'Ha';    for (let i = 0; i < count; i++) {     console.log(LAUGH);   } } 
like image 742
Arth Avatar asked Oct 03 '16 15:10

Arth


2 Answers

You should have

echo name_of_class::LAUGH 

Otherwise PHP will be looking for a global constant that was created with define().


followup:

You can also only define constants at the object level, e.g.

class foo {    const BAR = 'baz';  // valid     function foo() {       const BAR = 'baz'; // invalid. can't define constants INSIDE a method.    } } 
like image 85
Marc B Avatar answered Sep 28 '22 03:09

Marc B


No, there are no function-level constants in PHP. The closest thing is a 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 have also tried final $laugh = 'HA';

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

like image 22
ShiraNai7 Avatar answered Sep 28 '22 03:09

ShiraNai7