这些PHP概念初看可能晦涩难懂,将其整理列出旨在帮助开发者扫清障碍,让学习之路更加顺畅。
变量变量的解析规则与写法
1. 变量变量(Variable Variables)
variable_variables.php
复制代码 代码如下:
echo $$a.'\n';
$b = 'John';
$c = 'Mary';
$e = 'Joe';
$students = array('b','c','e');
echo ${$students[1]};
/*
foreach($students as $seat){
echo $$seat.'\n';
}
$$var[1]
${$var[1]} for #1
*/
$a = 'hello';将字符串'hello'赋值给变量$a后,$$a即等价于${hello},也就是$hello,其值为'hello everyone'。
对于$$students[1]这种写法,由于运算符优先级和解析逻辑,PHP解释器可能无法正确识别,导致输出异常或混乱。
推荐的规范写法是使用花括号明确层级:${$students[1]} = 'Mary';
数组元素的增删操作函数
2. 数组函数(Array Functions)
array_functions.php
复制代码 代码如下:
shift & unshift
';
$numbers = array(1,2,3,4,5,6);
print_r($numbers);
echo '
';
// 从数组头部移除第一个元素
// 索引将重新排序
$a = array_shift($numbers);
echo 'a: '.$a.'\n';
print_r($numbers);
// 向数组头部插入元素
// 返回新数组长度并重置数组索引
$b = array_unshift($numbers, 'first');
echo '\nb: '.$b.'\n';
print_r($numbers);
echo '';
echo 'pop & push
';
// 从数组尾部弹出最后一个元素
$c = array_pop($numbers);
print_r($numbers);
echo '
';
// 向数组尾部添加元素
$d = array_push($numbers, 'last');
echo 'd: '.$a.'\n';
print_r($numbers);更多数组函数参考
Unix时间戳的生成与格式化
3. 时间和日期 (Dates and Times) 创建Unix时间戳(自1970年1月1日以来的秒数)有三种常用方法: time(); 返回当前系统时间戳。 mktime($hr, $min, $sec, $month, $day, $year); 例如 mktime(6,30,0,5,22,2012) 返回2012年5月22日6点30分00秒的时间戳。 strtotime($string); 例如 strtotime("+1 day") 返回明天同一时刻的时间戳,也支持 'last Monday', 'last Year' 等相对时间描述。 checkdate($month, $day, $year); 验证日期合法性,如 checkdate(5,32,2012) ? 'true' : 'false'; 将返回 false。 获得时间戳后,需转换为可读格式(如2012/5/22),有两种方法:date($format, $timestamp) 和 strftime($format [,$timestamp])。 推荐使用strftime,例如 strftime("%Y-%m-%d %H:%M:%S"); 返回 2012-05-22 15:46:40。
更多时间日期参考
5. 服务器变量 (Server Variables) $_SERVER server_variables.php 复制代码 代码如下:
更多详细信息
静态变量与全局变量的作用域
6. 变量作用域 (Variable Scope: global static)
static_variables.php 复制代码 代码如下:
test();
echo '\n';
test();
echo '\n';
test();
echo '\n';
echo '';
function test1()
{
static $a = 0;
echo $a;$a++;
}
test1();
echo '\n';
test1();
echo '\n';
test1();
echo '\n';在test()函数中,变量$a未声明为静态,因此每次调用时不会保留$a++的结果,重复调用不会使$a累加。
而在test1()函数中,变量$a被声明为static $a = 0,成为静态变量。
引用说明:A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope.
静态变量仅存在于本地函数作用域内(即test1()函数体内),但当程序执行离开该作用域时,静态变量不会丢失其值,即$a会保持递增状态;当再次调用test1()时,$a的值已从上一次调用的结果开始(如$a=1)。
global_variables.php
复制代码 代码如下:
function Sum()
{
global $a, $b;
$b = $a + $b;
}
Sum();
echo $b;
echo '';
$a = 1;
$b = 2;
function Sum1()
{
$GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];
}
Sum1();
echo $b;引用说明:In PHP global variables must be declared global inside a function if they are going to be used in that function.
如果全局变量需要在函数内部使用,必须在该函数中使用global关键字进行声明。这样可以避免许多潜在的问题和麻烦。
引用传递与函数返回值引用
更多详细信息 7. 引用 (Reference) variable_reference.php 复制代码 代码如下:
';
$a = 'arist';
$b = &$a;
$b = 'ming';
echo "My name is:{$a}. And my mother call me {$b}.
";通过引用赋值后,修改$b的值也会同时改变$a的值,因为它们指向同一内存地址。
8. 向函数传递引用参数 (Pass Reference Variable to Function)
<?phpfunction ref_test(&$var){
return $var *= 2;
}
$a = 10;
ref_test($a);
echo $a;按引用传递参数时,传递的是变量的真实值而非副本(copy)。
因此,当调用函数ref_test($a)时,直接改变了外部$a的值,最终$a变为20。
9. 引用函数返回值 (Reference Function Return Value)
reference_function_return_value.php
<?phpfunction &increment(){
static $var = 0;$var++;
return $var;
}
$a =& increment(); // 1
increment(); // 2$a++; //3
increment(); // 4
echo "a: {$a}";首先定义一个返回引用的函数,在函数体内声明一个静态变量$var用于保存累加后的值。
$a =& increment(); 这条语句表示变量$a引用了函数increment()的返回值。这与之前的引用变量原理相同,可以将increment()函数视为一个变量,从而转化为 $a = & $b; 的形式。
因此,increment()函数和变量$a都指向同一个值,修改其中任何一个,都会影响另一个。
更多详细信息
对象 OOP
OOP中$this与静态方法的常见错误
1. Fatal error: Using $this when not in object context
这是初学者在学习OOP时常犯的错误,源于对类可访问性(Accessible)或作用域概念的理解不足。可以类比为:一个中国人在国外,若不属于任何特定文化群体且不通外语,便无法直接与当地人沟通,因为他们缺乏共同的语境。 那么错误是如何发生的呢?请看下面的例子:
复制代码 代码如下:
这个错误非常经典且实用,先来看static的定义:
Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static can not be accessed with an instantiated class object (though a static method can).
翻译:将类的属性或方法定义为静态(static)后,无需实例化该类即可直接访问。但被定义为静态的属性不能通过实例化的类对象(使用对象操作符 -> )来访问(尽管静态方法可以)。
例子说明: 第7行和第10行犯了同样的错误,即试图使用对象操作符来访问静态变量。根据定义,$this是一个伪变量,相当于object的一个实例。使用对象操作符 -> 访问静态成员就会报错。
同样,也不能使用静态操作符 :: 来访问非静态的公共变量。正确的访问方式见第14行和第25行:一种是在类定义内部通过 self:: (等同于 Trones::)访问,另一种是在类外部访问。
对于继承类,上述规则同样适用。
2. Fatal error: Call to private method
最近有一部很受欢迎的连续剧叫《权力的游戏》,剧中假设有三方人马争夺王冠胜利,分别是7个国王、平民和龙女。
下面的故事还有一个标题:类的可见性 (Visibility)。如果你知道最终答案,可以直接跳过解释部分。
复制代码 代码如下:
当static遇到private时,结合会产生复杂性,但也蕴含美感;就像抽象的人,或者大学老师讲的数学课(不过网易公开课的数学课很不错)。
如果想要龙女获得最终胜利,只需帮她一把,去掉第13行的 $this->getFire() 这部分代码即可。同理,你无法在静态函数中使用任何对象操作符。
如果你不构建大型框架和网站,像 Interface, Implement, abstract 等高级概念,了解与否对你影响不大。