2010-08-08 50 views
2

我是PHP OOP概念中的新人。第一件引起我注意的事情是,我不能在脚本开始时写一次php脚本给多个类。我的意思是PHP仅包含外部类一次

<?php 
include 'var.php'; 
class userSession{ 
    /* all the code */ 
    public function getVariables(){ 
    /* use of variables which are inside var.php */ 
    } 
    public function getOtherVariables(){ 
    /* use of variables which are inside var.php */ 
    } 
} 
?> 

这是行不通的。

我不得不这样做 -

<?php 
    class userSession{ 
     /* all the code */ 
     public function getVariables(){ 
     include 'var.php'; 
     /* use of variables which are inside var.php */ 
     } 
     public function getOtherVariables(){ 
     include 'var.php'; 
     /* use of variables which are inside var.php */ 
     } 
    } 
    ?> 

什么我失踪?

+0

var.php的内容是什么。 – 2010-08-08 11:13:50

+1

在第一个示例中,您将var.php的内容包含在全局空间中。 在第二个示例中,您将var.php的内容包含在您类的方法的本地空间中。 你究竟想在这里做什么? – 2010-08-08 11:15:19

+0

假设只有两个变量。 '<?php $ var1 =“hello”; $ VAR2 = “世界”; ?> – 2010-08-08 11:15:39

回答

4

如果这些变量在全局空间中定义的,那么你需要在你的类方法中引用它们在全球空间:

include 'var.php'; 
class userSession{ 
    /* all the code */ 
    public function getVariables(){ 
    global $var1, $var2; 
    echo $var1,' ',$var2,'<br />'; 
    $var1 = 'Goodbye' 
    } 
    public function getOtherVariables(){ 
    global $var1, $var2; 
    echo $var1,' ',$var2,'<br />'; 
    } 
} 

$test = new userSession(); 
$test->getVariables(); 
$test->getOtherVariables(); 

这不是一个好主意。全局变量的使用通常是不好的做法,并且表明您还没有真正理解OOP的原理。

在你的第二个例子,你定义变量在局部空间的各个方法

class userSession{ 
    /* all the code */ 
    public function getVariables(){ 
    include 'var.php'; 
    echo $var1,' ',$var2,'<br />'; 
    $var1 = 'Goodbye' 
    } 
    public function getOtherVariables(){ 
    include 'var.php'; 
    echo $var1,' ',$var2,'<br />'; 
    } 
} 

$test = new userSession(); 
$test->getVariables(); 
$test->getOtherVariables(); 

因为每个变量是本地方法空间内独立定义,在getVariables改变$ VAR1()没有

class userSession{ 
    include 'var.php'; 
    /* all the code */ 
    public function getVariables(){ 
    echo $this->var1,' ',$this->var2,'<br />'; 
    $this->var1 = 'Goodbye' 
    } 
    public function getOtherVariables(){ 
    echo $this->var1,' ',$this->var2,'<br />'; 
    } 
} 

$test = new userSession(); 
$test->getVariables(); 
$test->getOtherVariables(); 

此:在($ VAR1在getOtherVariables)

第三种方法是定义你的变量类的属性影响将变量定义为userClass空间中的属性,因此它们可以通过userClass实例中的所有方法访问。请注意使用$ this-> var1而不是$ var1来访问属性。如果有多个userClass实例,则每个实例中的属性可能不同,但在每个实例中,属性在该实例的所有方法中都是一致的。

+1

上有很多关于它的资源,我得到第三个选择的解析错误(意外的T_INCLUDE)。 :( – Dian 2011-05-02 06:32:15