2009-10-13 117 views
0

下面的代碼工作正常: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()函數來存儲全局會話變量。解決方案?

回答

3

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(); ?> 
+0

啊拍,那我想我不需要他們的任何地方存儲在類,因爲我可以在任何時候任何地方訪問裏面沒有他們這樣做。愚蠢的錯誤......對於許多編碼來說,我想讓我想起簡單的問題。感謝您的關注。 – payling 2009-10-13 15:35:40

5

在只能使用的方法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; 
?>