我是 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 */
}
}
?>
我缺少什么吗?
最佳答案
如果变量是在全局空间中定义的,那么您需要在类方法中的全局空间中引用它们:
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 实例,则每个实例中的属性可以不同,但在每个实例内,该实例的所有方法中的属性都是一致的。
关于PHP 仅包含外部类一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3434092/