Hướng dẫn dùng imput meaning trong PHP

Khái niệm về hằng số trong PHP

Hằng số là một tên (dịnh danh) cho một giá trị đơn giản. Gọi là hằng số bởi vì giá trị ứng với tên hằng sau khi định nghĩa là không đổi trong quá trình thi hành script. Mặc định hằng số có phân biệt chữ hoa chữ thường. Thông thường viết code thì ta nên đặt tên hằng số bằng các ký tự IN HOA. Một hằng số phải bắt đầu bằng một ký tự chữ  (a-Z) hoặc gạch dưới (_), theo sau không được chứa các ký tự đặc biệt.

Nội dung chính

  • Khái niệm về hằng số trong PHP
  • Định nghĩa hằng số với hàm define
  • Định nghĩa hằng với từ khóa const
  • Sự khác nhau giữa hằng số và biến
  • Các hằng số đặc biệt (Magic Constant) trong PHP
  • Các hằng số định nghĩa trước trong PHP
  • Table of Contents

Nội dung chính

  • Khái niệm về hằng số trong PHP
  • Định nghĩa hằng số với hàm define
  • Định nghĩa hằng với từ khóa const
  • Sự khác nhau giữa hằng số và biến
  • Các hằng số đặc biệt (Magic Constant) trong PHP
  • Các hằng số định nghĩa trước trong PHP

Nếu dùng biểu thức chính quy đề kiểm tra đặt tên là phù hợp, thì biểu thức đó là:

^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$

Định nghĩa hằng số với hàm define

Để định nghĩa một hằng số bạn phải sử dụng hàm define() với cú pháp của hàm đó như sau:

define ( string $name , mixed $value) : bool

Trong đó $name là tên hằng số, và $value là giá trí gán cho hằng số, giá trị hằng số phải là một trong các kiểu:  boolean, integer, float và string.

Để lấy giá trị hằng bạn chỉ cần chỉ ra tên hằng, hằng số có phạm vi toàn cục, có nghĩa là sau khi định nghĩa bạn có thể truy cập nó ở bất kỳ đâu.

Trong trường hợp bạn dùng biến lưu trữ tên hằng thì lấy giá trị của hằng bằng hàm constant($name).

<?php  define("FIRSTWEEKDAY", 'MONDAY'); echo FIRSTWEEKDAY, PHP_EOL; //Lấy hằng số bằng cách chỉ ra tên $firstweek = 'FIRSTWEEKDAY'; echo constant($firstweek), PHP_EOL; // Lấy hằng số có tên lưu trong biến $firstweek ?> 

Khi bạn định nghĩa một hằng số, nếu trước đó đã định nghĩa sẽ dẫn tới lỗi. Khi cần thiết, bạn có thể kiểm tra xem một hằng số đã được định nghĩa hay chưa bằng hàm defined($ten-hang-so);

// Kiểm tra xem hằng số MYCOLOR có tồn tại không, nếu không // thì bắt đầu định nghĩa if (!defined('MYCOLOR')) { define('MYCOLOR', 'Green'); }

Định nghĩa hằng với từ khóa const

Với PHP 5.3.0 trở đi thì có thể dùng từ khóa const để định nghĩa hằng số, từ PHP 7 còn có thể định nghĩa hằng số bằng một mảng các giá trị, ví dụ:

// Định nghĩa hằng số bằng từ khóa const const MONDAY = "THỨ HAI"; echo MONDAY, PHP_EOL; // hằng số là một mảng các ký tự const DAYOFWEEK = [ 'CHỦ NHẬT', 'THỨ HAI', 'THỨ BA', 'THỨ TƯ', 'THỨ NĂM', 'THỨ SAU', 'THỨ BẢY', ]; // Truy cập đọc hằng số echo DAYOFWEEK[6]; // THỨ BẢY

Dùng từ khóa const cũng là cách tạo hằng số cho một lớp ở phần lập trình hướng đối tượng PHP

Sự khác nhau giữa hằng số và biến

  • Tên hằng số thi không cần bắt đầu bằng ký tự dollar $ như biến.
  • Hằng số không thể sử dụng phép gán giá trị như biến (=), giá trị của nó phải được xác định duy nhất tại hàm define.
  • Hằng số có thể truy cập bất cứ ở đâu mà không giới hạn phạm vị như biến.
  • Ngay sau khi giá trị hằng thiết lập, nó không bị thay đổi hay định nghĩa lại nữa.

Các hằng số đặc biệt (Magic Constant) trong PHP

PHP cung cấp một số lượng lớn các hằng đã định nghĩa sẵn, một số hằng rất đặc biệt gọi là Magic constant.  Dưới đây là một số hằng Magic (ma thuật):

Tên hằngMô tả
__LINE__ Dòng hiện tại của php file.
__FILE__

Tên file đầy đủ của script đang thi hành.

__DIR__ Tên thư mục đầy đủ của file PHP
__FUNCTION__ Lấy tên của hàm đang chạy
__CLASS__ Tên của lớp đang chạy
__TRAIT__ Tên của trait đang chạy
__METHOD__ Lấy tên mothod của lớp
__NAMESPACE__ Lấy tên namspace
ClassName::clas Tên đầy đủ của một lớp

Các hằng số định nghĩa trước trong PHP

Khi PHP hoạt động có vô số hằng số, một số định nghĩa bởi nhân của PHP, một số do các thành phần mở rộng (Extension), để lấy các hằng số đã định nghĩa thì dùng hàm get_defined_constants, nó trả về mảng các hằng số có trong PHP đang hoạt động của bạn

$allConst = get_defined_constants(true); print_r($allConst);

Một số hằng số đã định nghĩa trước bởi nhân PHP tham khảo tại: reserved.constants, ví dụ PHP_EOL là ký tự xuống dòng.

Source code: const (Git), hoặc tải rphp-const

Table of Contents

  • Syntax
  • Predefined constants
  • Magic constants

A constant is an identifier (name) for a simple value. As the name suggests, that value cannot change during the execution of the script (except for magic constants, which aren't actually constants). Constants are case-sensitive. By convention, constant identifiers are always uppercase.

Note:

Prior to PHP 8.0.0, constants defined using the define() function may be case-insensitive.

The name of a constant follows the same rules as any label in PHP. A valid constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thusly: ^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$

It is possible to define() constants with reserved or even invalid names, whose value can only be retrieved with the constant() function. However, doing so is not recommended.

Example #1 Valid and invalid constant names

// Valid constant names
define("FOO",     "something");
define("FOO2",    "something else");
define("FOO_BAR""something more");// Invalid constant names
define("2FOO",    "something");// This is valid, but should be avoided:
// PHP may one day provide a magical constant
// that will break your script
define("__FOO__""something"); ?>

Note: For our purposes here, a letter is a-z, A-Z, and the ASCII characters from 128 through 255 (0x80-0xff).

Like superglobals, the scope of a constant is global. Constants can be accessed from anywhere in a script without regard to scope. 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.

wbcarts at juno dot com

10 years ago

11/14/2016 - note updated by sobak
-----

CONSTANTS and PHP Class Definitions

Using "define('MY_VAR', 'default value')" INSIDE a class definition does not work as expected. You have to use the PHP keyword 'const' and initialize it with a scalar value -- boolean, int, float, string (or array in PHP 5.6+) -- right away.

define

('MIN_VALUE', '0.0');   // RIGHT - Works OUTSIDE of a class definition.
define('MAX_VALUE', '1.0');   // RIGHT - Works OUTSIDE of a class definition.

//const MIN_VALUE = 0.0;         RIGHT - Works both INSIDE and OUTSIDE of a class definition.
//const MAX_VALUE = 1.0;         RIGHT - Works both INSIDE and OUTSIDE of a class definition.

class Constants
{
 
//define('MIN_VALUE', '0.0');  WRONG - Works OUTSIDE of a class definition.
  //define('MAX_VALUE', '1.0');  WRONG - Works OUTSIDE of a class definition.
const MIN_VALUE = 0.0;      // RIGHT - Works INSIDE of a class definition.
 
const MAX_VALUE = 1.0;      // RIGHT - Works INSIDE of a class definition. public static function getMinValue()
  {
    return
self::MIN_VALUE;
  }

  public static function

getMaxValue()
  {
    return
self::MAX_VALUE;
  }
}
?>

#Example 1:
You can access these constants DIRECTLY like so:
* type the class name exactly.
* type two (2) colons.
* type the const name exactly.

#Example 2:
Because our class definition provides two (2) static functions, you can also access them like so:
* type the class name exactly.
* type two (2) colons.
* type the function name exactly (with the parentheses).

#Example 1:
$min = Constants::MIN_VALUE;
$max = Constants::MAX_VALUE; #Example 2:
$min = Constants::getMinValue();
$max = Constants::getMaxValue(); ?>

Once class constants are declared AND initialized, they cannot be set to different values -- that is why there are no setMinValue() and setMaxValue() functions in the class definition -- which means they are READ-ONLY and STATIC (shared by all instances of the class).

warwick dot jm dot barnes at gmail dot com

2 years ago

The documentation says, "You can access constants anywhere in your script without regard to scope", but it's worth keeping in mind that a const declaration must appear in the source file before the place where it's used.

This doesn't work (using PHP 5.4):
foo();
const
X = 1;
function
foo() {
    echo
"Value of X: " . X;
}
?>
Result: "Value of X: X"

But this works:
const X = 1;
foo();
function
foo() {
    echo
"Value of X: " . X;
}
?>
Result: "Value of X: 1"

This is potentially confusing because you can refer to a function that occurs later in your source file, but not a constant. Even though the const declaration is processed at compile time, it behaves a bit like it's being processed at run time.

ewspencer at industrex dot com

19 years ago

I find using the concatenation operator helps disambiguate value assignments with constants. For example, setting constants in a global configuration file:

define('LOCATOR',   "/locator");
define('CLASSES',   LOCATOR."/code/classes");
define('FUNCTIONS', LOCATOR."/code/functions");
define('USERDIR',   LOCATOR."/user");
?>

Later, I can use the same convention when invoking a constant's value for static constructs such as require() calls:

require_once(FUNCTIONS."/database.fnc");
require_once(
FUNCTIONS."/randchar.fnc");
?>

as well as dynamic constructs, typical of value assignment to variables:

$userid  = randchar(8,'anc','u');
$usermap = USERDIR."/".$userid.".png";
?>

The above convention works for me, and helps produce self-documenting code.

-- Erich

gried at NOSPAM dot nsys dot by

6 years ago

Lets expand comment of 'storm' about usage of undefined constants. His claim that 'An undefined constant evaluates as true...' is wrong and right at same time. As said further in documentation ' If you use an undefined constant, PHP assumes that you mean the name of the constant itself, just as if you called it as a string...'. So yeah, undefined global constant when accessed directly will be resolved as string equal to name of sought constant (as thought PHP supposes that programmer had forgot apostrophes and autofixes it) and non-zero non-empty string converts to True.

There are two ways to prevent this:
1. always use function constant('CONST_NAME') to get constant value (BTW it also works for class constants - constant('CLASS_NAME::CONST_NAME') );
2. use only class constants (that are defined inside of class using keyword const) because they are not converted to string when not found but throw exception instead (Fatal error: Undefined class constant).

hafenator2000 at yahoo dot com

17 years ago

PHP Modules also define constants.  Make sure to avoid constant name collisions.  There are two ways to do this that I can think of.
First: in your code make sure that the constant name is not already used.  ex. if (! defined("CONSTANT_NAME")) { Define("CONSTANT_NAME","Some Value"); } ?>  This can get messy when you start thinking about collision handling, and the implications of this.
Second: Use some off prepend to all your constant names without exception  ex. ("SITE_CONSTANT_NAME","Some Value"); ?>

Perhaps the developers or documentation maintainers could recommend a good prepend and ask module writers to avoid that prepend in modules.

Andreas R.

15 years ago

If you are looking for predefined constants like
* PHP_OS (to show the operating system, PHP was compiled for; php_uname('s') might be more suitable),
* DIRECTORY_SEPARATOR ("\\" on Win, '/' Linux,...)
* PATH_SEPARATOR (';' on Win, ':' on Linux,...)
they are buried in 'Predefined Constants' under 'List of Reserved Words' in the appendix:
http://www.php.net/manual/en/reserved.constants.php
while the latter two are also mentioned in 'Directory Functions'
http://www.php.net/manual/en/ref.dir.php

Raheel Khan

7 years ago

class constant are by default public in nature but they cannot be assigned visibility factor and in turn gives syntax error

class constants {

    const

MAX_VALUE = 10;
        public const
MIN_VALUE =1;

}

// This will work
echo constants::MAX_VALUE;// This will return syntax error
echo constants::MIN_VALUE;
?>

Sumon Mahmud (Abu Taleb)

2 years ago

define('MYKEY', 'The value is from outside of class');
class Abc{

        const MAX = 10;

    public function __construct(){
        define('TEST', 'hello world! '); // using define function in class constructor
    }
    public function getOutput(){
        echo TEST . MYKEY . PHP_EOL; // accessing constants from outside of class
    }
}

$obj = new Abc();  // define function will call
$obj->getOutput(); // hello world! The value is from outside of class

echo Abc::MAX . PHP_EOL; // 10 - accessing constant using scope resolution

echo TEST; // hello world!  Because the constants is defined while constructor call

storm

17 years ago

An undefined constant evaluates as true when not used correctly. Say for example you had something like this:

settings.php
// Debug mode
define('DEBUG',false);
?>

test.php
include('settings.php');

if (

DEBUG) {
  
// echo some sensitive data.
}
?>

If for some reason settings.php doesn't get included and the DEBUG constant is not set, PHP will STILL print the sensitive data. The solution is to evaluate it. Like so:

settings.php
// Debug mode
define('DEBUG',0);
?>

test.php
include('settings.php');

if (

DEBUG == 1) {
  
// echo some sensitive data.
}
?>

Now it works correctly.

jcastromail at yahoo dot es

4 years ago

Performance of constants.  PHP 7.1.10 32 bits (Opcache active, windows 10 i7-64bits) but apparently the trends is the same with the 5.x

using a constant declared by DEFINE('CNS',value) : 0.63575601577759s
using a constant declared by const CNS=value : 0.61372208595276s
using a variable declared by $v=value : 0.51184010505676s

In average, the use of DEFINE and CONST is around the same with some sightly  better performance of CONST instead of DEFINE. However, using a variable is around 10-50% better than to use a constant.  So, for a performance intensive task, constant is not the best option.

$p1=microtime(true);
$x=0;
for($i=0;$i<50000000;$i++) {
    $x+=CNS;
}
$p2=microtime(true);

mparsa1372 at gmail dot com

1 year ago

//Syntax of define constant in php
//define(name, value, case-insensitive);

//it will print 100 in output

define('BOOK',100);
echo
BOOK;//it will print 200 in output
define('book', 200 , true);
echo
book;//results of all are the same
echo '
'
;
echo
BOOK;
echo
'
'
;
echo
book;

php at webflips dot net

8 years ago

It is perfectly valid to use a built-in PHP keyword as a constant name - as long as you the constant() function to retrieve it later:

define('echo', 'My constant value');

echo

constant('echo'); // outputs 'My constant value'
?>