我是一个PHP OOP概念的新手。最吸引我眼球的事情之一是,我不能仅仅通过在脚本的开头编写一次来将一个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 */
}
}
?>我遗漏了什么吗?
发布于 2010-08-08 19:27:16
如果变量是在全局空间中定义的,那么您需要在类方法的全局空间中引用它们:
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对getOtherVariables()中的$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();这将变量定义为userClass空间中的属性,因此userClass实例中的所有方法都可以访问它们。注意,使用$this->var1而不是$var1来访问属性。如果有多个userClass实例,则每个实例中的属性可以不同,但在每个实例中,该实例的所有方法中的属性是一致的。
https://stackoverflow.com/questions/3434092
复制相似问题