33

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);
  }
}
Arth
  • 12,789
  • 5
  • 37
  • 69

4 Answers4

16

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.
   }
}
Marc B
  • 356,200
  • 43
  • 426
  • 500
  • still giving error, may be i am doing in a wrong way:-https://eval.in/654344 . correct me – Alive to die - Anant Oct 03 '16 at 15:31
  • Cool, that's what I experienced, but is there anyway to mark a local variable as read-only? – Arth Oct 03 '16 at 15:38
  • it's a local variable. it can't be accessed from "outside" the function, so what's the point of making it read only? If you want it read only, then don't write to it (except for initialization). – Marc B Oct 03 '16 at 15:41
  • 1
    For the same reason I wouldn't use a public class variable as a class constant.. I want to stop myself and other team members from writing to it. I was also curios.. I guess commenting a local variable is probably as close as I'm going to get though! – Arth Oct 03 '16 at 15:49
12

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.

Shira
  • 6,392
  • 2
  • 25
  • 27
  • 4
    I normally find the documentation doesn't specify things that aren't there.. and as a result it isn't easy to find rarely used constructs. I was primarily using those syntax attempts to demonstrate the kind of functionality I was hoping for. – Arth Oct 03 '16 at 15:45
2

As of PHP 7, anonymous classes enable to provide immutable variables somehow scoped at a function level:

# This will work as expected
function fulfill() {
  $immutable = new class { const value = 42; };
  return $immutable::value;
}

# This will compile, but what would one expect?
function misbehave() {
  $immutable = new class { const value = 7; };
  $immutable->value = 666;
  return $immutable::value;
}

fulfill(); // => 42
misbehave(); // => 7

So while misbehave does compile, it won’t allow the anonymous class constant to be changed, but PHP didn’t generate any warning or error: the attempt to change the $immutable::value just failed silently.

Also, the resulting syntax is, to say the least, very convoluted.

All that considered, it would most likely more wise to avoid an extensive use of this facility, but it nonetheless responds positively to the question: yes, PHP allows to define a local constant within a function.

Related resources

psychoslave
  • 2,783
  • 3
  • 27
  • 44
0

I think you're confusing const with scope here.

function foo() {
    $x = 1;
}

I don't need to declare $x as a const because it's already scoped to just foo(). I would have to explicitly raise it to the global scope to use it elsewhere (which is a bad idea for many reasons). $x can be changed, but only if you do so within your function, or edit the code.

Ironically, constants set by using define are globally scoped, with const generally being global, provided you're using an autoloader

miken32
  • 42,008
  • 16
  • 111
  • 154
Machavity
  • 30,841
  • 27
  • 92
  • 100
  • hmmm, could be wrong but I think they are more desiring the "read-only" and "reserved once" aspects of const. still this is an important insight as class const, global const and define are all effectively global constants. So even if you have to declare const in the parent scope of a function, effectively there's no real difference in PHP. – That Realty Programmer Guy Jul 24 '22 at 04:02