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); } }
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. } }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With