For example I have class A in file a.php
namespace Path\To;
class A {
const SOME_VAR = 'value';
// many functions
}
And I have class B in file b.php
use Path\To\A;
class B {
public function foo() {
$i = 1;
$i = 2;
$i = 3;
// other code
$someVar = A::SOME_VAR;
}
// other functions
}
Which time in executing function foo
constant variable SOME_VAR
loads in RAM. On first line of function foo or on line $someVar = A::SOME_VAR;
or line use Path\to\A;
or elsewhere?
a.php
is read, parsed and executed when $someVar = A::SOME_VAR;
is executed inside b.php
. That is also when the 'value'
string is loaded into memory.
At that same time, everything about class A
is loaded. If you where to add const SECOND_VAR = 'another-value';
to class A
, once $someVar = A::SOME_VAR;
has been executed there is also a bit of RAM that contains 'another-value'
.
What the use Path\To\A;
line does, is just tell PHP "if class A
is requested, what they mean is \Path\To\A
". You can add use Some\Non\ExistentClass
and use Some\Class\That\Has\ASyntaxErrorInTheCode
, and nothing will change, because as long as you don't try to actually do anything with ExistentClass
or ASyntaxErrorInTheCode
PHP will never read the files that those classes are in.
Memory is being allocated the first time you request the value of the variable. An easy way to test it is the following:
Create a file named Foo.php
<?php
class Foo {
// As of PHP 7.1.0
public const BAR = 'bar';
private const BAZ = 'baz';
}
?>
Use the following file anywhere you want.
And then type the following 2 lines:
$x = FOO::BAR;
$y = FOO::BAZ; // <- this will cause an error, since the variable is private
No error will occur during the use of the file, or while retrieving the value of the previous BAR
variable. This way you can identify that PHP knows nothing about that variable before you attempt to access its value.