PHP如何:会话变量保存到一个静态类变量
下面的代码工作正常:PHP如何:会话变量保存到一个静态类变量
<?php session_start();
$_SESSION['color'] = 'blue';
class utilities
{
public static $color;
function display()
{
echo utilities::$color = $_SESSION['color'];
}
}
utilities::display(); ?>
这就是我想要的,但不工作:
<?php session_start();
$_SESSION['color'] = 'blue';
class utilities {
public static $color = $_SESSION['color']; //see here
function display()
{
echo utilities::$color;
} } utilities::display(); ?>
我得到这个错误: Parse error: syntax error, unexpected T_VARIABLE in C:\Inetpub\vhosts\morsemfgco.com\httpdocs\secure2\scrap\class.php on line 7
PHP不喜欢将会话变量存储在函数之外。为什么?这是一个语法问题还是什么?我不想实例化对象,因为只需调用实用程序函数,我需要一些会话变量来全局存储。我不想在每次运行函数时调用一个init()
函数来存储全局会话变量。解决方案?
从PHP manual: -
Like any other PHP static variable, static properties may only be initialized using a literal or constant; expressions are not allowed. So while you may initialize a static property to an integer or array (for instance), you may not initialize it to another variable, to a function return value, or to an object.
你说你需要你的会话变量,以在全球范围内存储?他们是$_SESSION
就是所谓的"super global"
<?php
class utilities {
public static $color = $_SESSION['color']; //see here
function display()
{
echo $_SESSION['color'];
}
}
utilities::display(); ?>
在只能使用的方法SESSION类...
其实,如果你想要做的事的一类,你必须编写它在一种方法中...
一个类不是一个函数。它有一些变量 - 作为属性 - 和一些函数 - 作为方法 - 你可以定义变量,你可以初始化它们。但你不能如果你想设置他们这样你必须使用构造函数...例如
public static $var1; // OK!
public static $var2=5; //OK!
public static $var3=5+5; //ERROR
做任何操作对他们的方法之外... (但请记住:构造不调用,直到创建对象...)
<?php
session_start();
$_SESSION['color'] = 'blue';
class utilities {
public static $color;
function __construct()
{
$this->color=$_SESSION['color'];
}
function display()
{
echo utilities::$color;
}
}
utilities::display(); //empty output, because constructor wasn't invoked...
$obj=new utilities();
echo "<br>".$obj->color;
?>
啊拍,那我想我不需要他们的任何地方存储在类,因为我可以在任何时候任何地方访问里面没有他们这样做。愚蠢的错误......对于许多编码来说,我想让我想起简单的问题。感谢您的关注。 – payling 2009-10-13 15:35:40