PHP 类继承包含文件中的变量
我有这样的:
class Class2 extends Class1 {
.....
function __construct() {
parent::__construct();
$var_in_included_file;
}
}
class Class1 {
function __construct() {
include_once('my_file.php')
}
.....
}
my_file.php:
$var_in_included_file=10;
问题是我无法接收 $var_in_included_file 的值。有没有办法在不添加许多代码的情况下接收这个值,例如:
$this->var=$var_in_included_file ....?
因为我有数千个变量。 谢谢。 更抽象的问题是: 在一些文件中,我收到(来自 $_POST)近 500 个变量。 这些变量已以复杂的方式详细阐述。为了简化这个阐述,我需要创建类继承树 - 但在这种情况下,如果不将它们分配给类变量,这些变量将不会在子类中看到 - 但这会产生大量代码。
I have like:
class Class2 extends Class1 {
.....
function __construct() {
parent::__construct();
$var_in_included_file;
}
}
class Class1 {
function __construct() {
include_once('my_file.php')
}
.....
}
my_file.php:
$var_in_included_file=10;
The problem is that I cannot receive value of $var_in_included_file. Is there a way to receive this value without add many codice like:
$this->var=$var_in_included_file ....?
Because I have many thousands of variables.
Thanks.
More abstract the problem is:
in some file I received (from $_POST) near 500 variable.
These variables have be elaborated in complicated way. For simplify this elaborating I need create tree of class inheritans - but in this case these variables will not seen in child classes without assigning them to class variables - but this produses enormous volume of code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在第一类中,将变量分配给类变量:
现在可以通过
$this->someVariable
在子类中访问该变量。快乐编码,祝你好运
In class one, assign your variables to class variables:
Now that variable is accessible in child class, through
$this->someVariable
.Happy coding, good-luck
正如
include()
中所述变量范围,当您在__construct()
方法,您所包含的文件中变量的范围仅限于 __construct() 方法,而不是类。您的选择是更改包含文件的内容以在变量名称前面包含
$this->
(即$this->var_in_included_file = 10;
code>) 或在__construct()
方法中添加$this->var_in_included_file = $var_in_included_file;
。As explained in
include()
and variable scopes, when you include a file in your__construct()
method, the scope of the variables in the file you're including is limited to the__construct()
method, not the class.Your options would be to either change the content of the included file to include a
$this->
in front of the variable name (i.e.$this->var_in_included_file = 10;
) or add a$this->var_in_included_file = $var_in_included_file;
in your__construct()
method.不可能
Is not possible