能否在类外部调用static属性?为何PHP静态属性取值为空?
问题解答
1. 类外部能否读取static变量?
可以。只要static变量的访问权限为public(PHP类成员默认是public),就能在类外部通过类名::$静态变量名的方式直接读取,无需实例化类。
2. 为什么show.php中静态变量返回空值?
核心原因是PHP的HTTP请求是独立无状态的:
- 提交表单到
add_name.php时,服务器会启动一个独立的PHP进程处理该请求,此时设置的Person::$name仅存在于当前进程的内存中。 - 点击链接跳转到
show.php时,这是一个全新的HTTP请求,服务器会启动另一个PHP进程,重新加载person.class.php,此时Person::$name会被重置为默认的空值,因此输出为空。
3. 解决方法
要在不同请求之间共享数据,需要将数据持久化存储,常见方案如下:
方案一:使用Session
修改代码实现跨请求共享:
add_name.php:
<?php //add_name.php session_start(); require("person.class.php"); $name = $_POST["name"]; Person::setName($name); $_SESSION['person_name'] = Person::$name; echo(Person::$name." now is on static property name. <a href='show.php'>See the name</a>"); ?>
show.php:
<?php //show.php session_start(); require("person.class.php"); Person::$name = $_SESSION['person_name'] ?? ''; echo("The name is:".Person::$name); ?>
方案二:使用文件/数据库存储
如果需要长期保存数据,可将值写入文件或存入数据库:
- 示例(文件存储):
add_name.php新增存储逻辑:file_put_contents('name_storage.txt', Person::$name);show.php读取数据:Person::$name = file_get_contents('name_storage.txt') ?? '';
内容的提问来源于stack exchange,提问作者Luis Miguel
相关产品推荐
相关产品推荐

