Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing PHP Class Constants

Tags:

oop

php

The PHP manual says

Like static members, constant values can not be accessed from an instance of the object.

which explains why you can't do this

$this->inst = new Classname();
echo $this->inst::someconstant;

but then why does this work?

$this->inst = new Classname();
$inst = $this->inst;
echo $inst::someconstant;
like image 518
pettazz Avatar asked Mar 27 '11 06:03

pettazz


People also ask

How do you call a class constant in PHP?

PHP - Class Constants Constants cannot be changed once it is declared. Class constants can be useful if you need to define some constant data within a class. A class constant is declared inside a class with the const keyword. Class constants are case-sensitive.

How can I get constant in PHP?

To access the class constant, you use the name of the class (in this case mathematics), followed by 2 colons (::), followed by the name of the constant (in this case PI). In this code, we echo out the constant, so an echo precedes this code. Usually by convention, constants are put in all uppercase.

Can you redefine constants in PHP?

Constants cannot be defined by simple assignment, they may only be defined using the define() function. Constants may be defined and accessed anywhere without regard to variable scoping rules. Once the Constants have been set, may not be redefined or undefined.

Can we declare constants in PHP by using below syntax $constant?

Unfortunately, this means you cannot use the const keyword within conditional statements. Like using the define() function, you should write the constant name in uppercase letters or numbers. The basic syntax for using the const keyword to define a constant in PHP is as we have shown it below.


1 Answers

From the PHP interactive shell:

php > class Foo { const A = 'a!'; }
php > class Bar { public $foo; }
php > $f = new Foo;
php > $b = new Bar;
php > $b->foo = $f;
php > echo $b->foo::A;
PHP Parse error:  syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM, expecting ',' or ';' in php shell code on line 1

The reason that the former syntax fails is that the PHP parser doesn't know how to resolve the double-colon after the property reference. Whether or not this is intentional is unknown.

The latter syntax works because it's not going through the property directly, but through a local variable, which the parser accepts as something it can work with:

php > $inst = $b->foo;
php > echo $inst::A;
a!

(Incidentally, this same restriction is in place for anonymous functions as properties. You can't call them directly using parens, you have to first assign them to another variable and then call them from there. This has been fixed in PHP's trunk, but I don't know if they also fixed the double colon syntax.)

like image 56
Charles Avatar answered Sep 21 '22 14:09

Charles