【问题标题】:PHP class inherit variables in included filePHP类继承包含文件中的变量
【发布时间】:2011-09-22 18:03:06
【问题描述】:

我喜欢:

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 个变量。 这些变量已经以复杂的方式进行了阐述。为了简化这一阐述,我需要创建类继承树 - 但在这种情况下,如果不将它们分配给类变量,这些变量将不会在子类中看到 - 但这会产生大量代码。

【问题讨论】:

    标签: php class file include extends


    【解决方案1】:

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

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

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

    编码愉快,祝你好运

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:
        Class1 {
        
        include_once('my_file.php')
        .....
        }
        

        不可能

        【讨论】:

        • 还缺少class 关键字?
        • 为了简洁,明确是在函数__construct() { }
        • 这不是用于语法检查的代码——这是问题的意义——有没有办法接收对隐藏在父类中的许多变量的访问。
        • 所以答案是——不,唯一的办法是$this->varName
        猜你喜欢
        • 2012-07-13
        • 2011-03-25
        • 1970-01-01
        • 2015-10-31
        • 2017-11-22
        • 2022-08-04
        • 1970-01-01
        • 2018-02-24
        • 1970-01-01
        相关资源
        最近更新 更多