PHP 5: const vs static
In the context of a class, static variables are on the class scope (not the object) scope, but unlike a const, their values can be changed.
class ClassName {
static $my_var = 10; /* defaults to public unless otherwise specified */
const MY_CONST = 5;
}
echo ClassName::$my_var; // returns 10
echo ClassName::MY_CONST; // returns 5
ClassName::$my_var = 20; // now equals 20
ClassName::MY_CONST = 20; // error! won't work.
Public, protected, and private are irrelevant in terms of consts (which are always public); they are only useful for class variables, including static variable.
- public static variables can be accessed anywhere via ClassName::$variable.
- protected static variables can be accessed by the defining class or extending classes via ClassName::$variable.
- private static variables can be accessed only by the defining class via ClassName::$variable.
Edit: It is important to note that PHP 7.1.0 introduced support for specifying the visibility of class constants.
PHP OOP - constant vs static variables?
Static is for:
class properties or methods as static makes them accessible without needing an instantiation of the class
So, the value returned by a static member may differ. For example, you can call a static method with different result depending of what parameters you pass to it.
Constants value:
must be a constant expression, not (for example) a variable, a property, a result of a mathematical operation, or a function call.
So, it always return the same result when you call it
About create an object and extending a class, when you "create an object" you make an instance of a class. When you extend a class, you create an other class who:
inherits all of the public and protected methods from the parent class. Unless a class overrides those methods, they will retain their original functionality.
I hope it help you.
const' vs. 'static' in PHP
The static variable can be changed, the const one cannot. The main consideration should be given to whether the config variables should be able to be altered at run time, not which is faster. The speed difference between the two (if there is any) is so minimal it isn't worth thinking about.
In PHP, what is the difference between final static and const?
final
The methods or classes can not be modified by a child class. This prevents class inheritance, method-overriding and/or redefinition of methods.
Only class definitions and/or methods inside a class can be defined as
final
.
static
Declares class methods or properties as a static value so that you have access to them without instantiating an object. These are shared between parent and child-classes.
A class definition can not be
static
unlikefinal
.
const
These create a constant value for a class. The constant values will get changed and can NOT be changed by a method in either parent or child-class.
Class constants are allocated per instance of the class.
const
is a type specifier in itself. It can not be put along with public
/private
/static
etc. final
, as mentioned before can be used along with any method or class definitions and hence; applicable with all of them. static
can not be applied to class definitions but can be used for class properties.
UPDATE
modifiers are allowed for class constants since PHP 7.1.0.
class Foo {
public const bar = 5;
private const baz = 6;
}
To summarise,
final static
can not be used to define something like:class X {
final static x = 5;
}
which is why you have a
const
.
PHP | define() vs. const
As of PHP 5.3 there are two ways to define constants: Either using the const
keyword or using the define()
function:
const FOO = 'BAR';
define('FOO', 'BAR');
The fundamental difference between those two ways is that const
defines constants at compile time, whereas define
defines them at run time. This causes most of const
's disadvantages. Some disadvantages of const
are:
const
cannot be used to conditionally define constants. To define a global constant, it has to be used in the outermost scope:if (...) {
const FOO = 'BAR'; // Invalid
}
// but
if (...) {
define('FOO', 'BAR'); // Valid
}Why would you want to do that anyway? One common application is to check whether the constant is already defined:
if (!defined('FOO')) {
define('FOO', 'BAR');
}const
accepts a static scalar (number, string or other constant liketrue
,false
,null
,__FILE__
), whereasdefine()
takes any expression. Since PHP 5.6 constant expressions are allowed inconst
as well:const BIT_5 = 1 << 5; // Valid since PHP 5.6 and invalid previously
define('BIT_5', 1 << 5); // Always validconst
takes a plain constant name, whereasdefine()
accepts any expression as name. This allows to do things like this:for ($i = 0; $i < 32; ++$i) {
define('BIT_' . $i, 1 << $i);
}const
s are always case sensitive, whereasdefine()
allows you to define case insensitive constants by passingtrue
as the third argument (Note: defining case-insensitive constants is deprecated as of PHP 7.3.0 and removed since PHP 8.0.0):define('FOO', 'BAR', true);
echo FOO; // BAR
echo foo; // BAR
So, that was the bad side of things. Now let's look at the reason why I personally always use const
unless one of the above situations occurs:
const
simply reads nicer. It's a language construct instead of a function and also is consistent with how you define constants in classes.const
, being a language construct, can be statically analysed by automated tooling.const
defines a constant in the current namespace, whiledefine()
has to be passed the full namespace name:namespace A\B\C;
// To define the constant A\B\C\FOO:
const FOO = 'BAR';
define('A\B\C\FOO', 'BAR');Since PHP 5.6
const
constants can also be arrays, whiledefine()
does not support arrays yet. However, arrays will be supported for both cases in PHP 7.const FOO = [1, 2, 3]; // Valid in PHP 5.6
define('FOO', [1, 2, 3]); // Invalid in PHP 5.6 and valid in PHP 7.0
Finally, note that const
can also be used within a class or interface to define a class constant or interface constant. define
cannot be used for this purpose:
class Foo {
const BAR = 2; // Valid
}
// But
class Baz {
define('QUX', 2); // Invalid
}
Summary
Unless you need any type of conditional or expressional definition, use const
s instead of define()
s - simply for the sake of readability!
PHP const/static variables not usable in static context by parent class
PHP5.3 introduced late static binding — that's what you're looking for.
class ParentClass {
public function getAll() {
var_dump('Get all from ' . static::TABLE_NAME);
}
}
class ChildClass extends ParentClass {
const TABLE_NAME = 'my_table_name';
}
$c = new ChildClass();
$c->getAll(); // Get all from my_table_name
EDIT:
However you should design your classes a little bit different. The above solution relies on language dynamics (you can refer to something (eg. a class constant) that doesn't even exists). In such a simple example everything is fine but in real word cases this leads to producing horrible and hard to maintain code.
It'd be better to force the delivered class (ChildClass
) to implement some method that returns table name:
abstract class ParentClass {
// getAll function
abstract protected function getTableName();
}
class ChildClass extends ParentClass {
// You have to implement this method
protected function getTableName() {
return 'table name';
}
}
Can you use static constants inside classes in PHP?
You can use const in class like this:
class Patterns {
const EMAIL = "/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix";
const INT = "/^\d+$/";
const USERNAME = "/^\w+$/";
}
And can access USERNAME
const like this:
Patterns::USERNAME
Constants in PHP5
I understand you want to assign a mathematical expression to a constant.
Like:
const FOO = 2.0*pi();
PHP constants can only contain scalar values. If you want other classes to use shared information, you will have to use static functions/methods for this.
Example:
static public function foo()
{
return 2.0*pi();
}
Related Topics
Connect to PHP Server Using Swift
Swift Sync Data of Core Data an MySQL Database
Automatically Detect User's Current Local Time with JavaScript or PHP
Data from Two Tables with Same Column Names
How to Set an Arrays Internal Pointer to a Specific Position? PHP/Xml
How to Alias the Name of a Column in Eloquent
What Are the Valid Characters in PHP Variable, Method, Class, etc Names
How to Notify a User After an Access_Control Rule Redirects
Relative Path in Require_Once Doesn't Work
When Do I Use Static Variables/Functions in PHP
Laravel Migration Table Already Exists, But I Want to Add New Not the Older
Codeigniter Check for User Session in Every Controller