Home What does this actually mean by "Class constants are allocated once per class, and not for each class instance"?
Reply: 2

What does this actually mean by "Class constants are allocated once per class, and not for each class instance"?

SerialKisser
1#
SerialKisser Published in 2017-12-07 18:13:14Z

I come across the following sentence from PHP Manual :

"Class constants are allocated once per class, and not for each class instance".

What does this statement actually mean?

I know that class constants are defined on per-class basis and they are accessible only within the context of base class and class inherited from it/class implementing the interface(i.e. if class constants are declared in an interface).

But I seriously didn't get the meaning of this sentence

"Class constants are allocated once per class, and not for each class instance".

Can someone please make me understand the actual, practical meaning of this statement?

I searched google and look for code examples demonstrating this but I couldn't get much useful stuff from the internet.

So, someone please explain the meaning of this statement in an simple, lucid and easy to understand explanation along with the working code examples..

Thank You.

Reference Link : https://secure.php.net/manual/en/language.oop5.constants.php

Devon
2#
Devon Reply to 2017-12-07 22:21:36Z

Constants are defined once when the class is first loaded, not every time it is instantiated.

$inst1 = new Class(); // constants are defined (assuming the class has never been loaded before this)
$inst2 = new Class(); // constants are not re-defined

This kind of goes hand in hand with the fact that constants won't ever change from start to finish.

Another way of looking at it is:

$inst1::CONSTANT is the same as $inst2::CONSTANT is the same as Class::CONSTANT
Ice76
3#
Ice76 Reply to 2017-12-07 18:32:43Z

Basically, what that sentence means, is that a constant is made and it resides in its class. An object, an instance, will have access to those constants but they are not re-made whenever a new object is made. Constants are static.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.249408 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO