1

我喜欢:

class Class2 extends Class1 {
.....
 function __construct() {
 parent::__construct();
   $var_in_included_file;
}   
}

class Class1 {
function __construct() {
 include_once('my_file.php')
}
.....
}

我的文件.php:

$var_in_included_file=10;

问题是我无法收到 $var_in_included_file 的值。有没有办法在不添加许多代码的情况下接收这个值:

$this->var=$var_in_included_file ....? 

因为我有成千上万个变量。谢谢。更抽象的问题是:在我收到的一些文件中(来自 $_POST)接近 500 个变量。这些变量已经以复杂的方式进行了阐述。为了简化这一阐述,我需要创建类继承树 - 但在这种情况下,如果不将它们分配给类变量,这些变量将不会在子类中看到 - 但这会产生大量代码。

4

3 回答 3

2

在第一类中,将变量分配给类变量:

class Class1{
   private $someVariable;

 public function __construct(){
    include_once 'my_file.php';
     // variable declared in my_file.php        
    $this->someVariable = $someVariable;        
    }       

}

现在该变量可以在子类中通过$this->someVariable.

快乐的编码,祝你好运

于 2011-06-25T21:03:09.660 回答
1

正如include()variable scopes中所解释的,当您在方法中包含文件时,您所包含的文件中__construct()变量的范围仅限于__construct()方法,而不是类。

您的选择是更改包含文件的内容以$this->在变量名(即)前包含 a 或在您的方法中$this->var_in_included_file = 10;添加 a 。$this->var_in_included_file = $var_in_included_file;__construct()

于 2011-06-25T20:59:33.653 回答
0
Class1 {

include_once('my_file.php')
.....
}

不可能

于 2011-06-25T20:48:30.403 回答