Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP constants with local scope

Tags:

php

In PHP is it possible to have constants with local scope? Is yes please provide a small example.

like image 920
Zacky112 Avatar asked Jul 09 '10 06:07

Zacky112


People also ask

What is the scope of a class constant in PHP?

For more information on scope, read the manual section on variable scope . Note: As of PHP 7.1.0, class constant may declare a visibility of protected or private, making them only available in the hierarchical scope of the class in which it is defined. Using "define ('MY_VAR', 'default value')" INSIDE a class definition does not work as expected.

Is it possible to have constants with local scope?

In PHP is it possible to have constants with local scope? Is yes please provide a small example. Yes, but only using a class. About Kalium's comment, if you're on PHP 5.3, you can indeed also use namespaces:

How to define PHP constants?

PHP constants follow the same PHP variable rules. For example, it can be started with a letter or underscore only. Conventionally, PHP constants should be defined in uppercase letters. Note: Unlike variables, constants are automatically global throughout the script. Use the define () function to create a constant. It defines constant at run time.

What is the default visibility of class constants in PHP?

The default visibility of class constants is public . Class constants can be redefined by a child class. As of PHP 8.1.0, class constants cannot be redefined by a child class if it is defined as final . It's also possible for interfaces to have constants.


1 Answers

Yes, but only using a class.

class Foo
{
    const BAR = 'hello, world';
}
print Foo::BAR;

About Kalium's comment, if you're on PHP 5.3, you can indeed also use namespaces:

namespace Foo;
const BAR = 1;
like image 93
Macmade Avatar answered Oct 05 '22 09:10

Macmade