简体   繁体   English

Php中全局变量,常量,定义变量,静态变量和非静态变量之间的差异

[英]Difference between global variable, constant, define variable, static variable, and Non static Variable in Php

在采访中有人问我这个问题,请对此作一些答复:Php全局变量,常量,define(定义一个常量),static变量和Nonstatic变量中所有这些类型的变量之间的区别是什么?

Global variables refer to any variable that is defined outside of the function. 全局变量是指在函数外部定义的任何变量。

Global variables can be accessed from any part of the script ie inside and outside of the function. 可以从脚本的任何部分(即函数的内部和外部)访问全局变量。 So, a global variable can be declared just like other variable but it must be declared outside of function definition 因此,可以像其他变量一样声明全局变量,但必须在函数定义之外声明它

Constant is an identifier (name) for a simple value. 常量是简单值的标识符(名称)。 The value cannot be changed during the script. 该值不能在脚本期间更改。 A constant is case-sensitive by default. 常量默认情况下区分大小写。 By convention, constant identifiers are always uppercase. 按照约定,常量标识符始终为大写。 No '$' sign used for declare constant. 没有用于声明常量的'$'符号。

const PI=3.14;

define('PI',3.14);

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
}
`

The fundamental difference between those two ways is that constant defines constants at compile time, whereas define defines them at run time. 这两种方式之间的根本区别是,常量在编译时定义常量,而define在运行时定义常量。

Static: Normally, when a function is completed/executed, all of its variables are deleted. 静态:通常,当一个函数完成/执行时,其所有变量都将被删除。 However, sometimes we want a local variable NOT to be deleted. 但是,有时我们希望不删除局部变量。 We need it for a further job.For that purpose we use static keyword. 我们需要它来做进一步的工作。为此,我们使用static关键字。

Non Static: When a function is completed/executed, all of its variables are deleted.And, initialized again. 非静态:函数完成/执行后,将删除其所有变量,然后再次初始化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM