Php 从类访问在其他文件中定义的变量
我想知道是否有一种方法可以从PHP中的类访问其他文件中定义的变量 例如: 文件_01.phpPhp 从类访问在其他文件中定义的变量,php,variables,scope,global-variables,global,Php,Variables,Scope,Global Variables,Global,我想知道是否有一种方法可以从PHP中的类访问其他文件中定义的变量 例如: 文件_01.php <?php $a = 42; ?> <?php require_once('file_01.php'); class mnyClass { private $myVar; function __construct($var = $a) { $this->myVar = $
<?php
$a = 42;
?>
<?php
require_once('file_01.php');
class mnyClass
{
private $myVar;
function __construct($var = $a)
{
$this->myVar = $var;
}
function getVar()
{
return $this->var;
}
function setVar($var)
{
$this->myVar = $var;
}
}
?>
文件_02.php
<?php
$a = 42;
?>
<?php
require_once('file_01.php');
class mnyClass
{
private $myVar;
function __construct($var = $a)
{
$this->myVar = $var;
}
function getVar()
{
return $this->var;
}
function setVar($var)
{
$this->myVar = $var;
}
}
?>
显然,我的课更复杂。我选择这个例子是为了更好地理解我想做什么;)
提前谢谢。您不能这样做:
function __construct($var = $a)
{
$this->myVar = $var;
}
你能做的就是通过它:
<?php
require_once('file_01.php');
$mnyClass = new mnyClass($a);// the torch has been passed!
class mnyClass
{
private $myVar;
function __construct($var = null)
{
$this->myVar = $var;
}
function getVar()
{
return $this->var;
}
function setVar($var)
{
$this->myVar = $var;
}
}
?>
您可以通过全局变量访问变量: 编辑:再详细一点-
function __construct() {
$this->myVar = $GLOBALS['a'];
}
听起来您正在设置一些应用程序默认值。将这些定义为常量可能是有意义的: 文件_01.php:
define('DEFAULT_VALUE_FOR_A', 42);
文件_02.php
class myClass
{
function __construct($var = DEFAULT_VALUE_FOR_A) {
}
}
最后,我使用这种方法:
<?php
require_once('file_01.php');
class myClass {
private $myVar;
function __construct($var = NULL)
{
global $a;
if($var == NULL)
$this->myVar = $a;
else
$this->myVar = $var;
}
}
?>
我在构造函数中将变量
$a
声明为全局变量,将$var
的默认值设置为NULL,并检查是否使用参数($var==NULL)调用构造函数。首先,感谢大家的回答。事实上,我想设置应用程序默认值,但要使用关联数组。define()
方法不将数组作为参数。我知道$GLOBALS
变量,但它不能在构造函数参数中使用:/因此,我决定在构造函数中使用$GLOBALS,并对参数进行空测试。出于好奇,为什么不建议使用它?@Frank您不能对全局变量进行范围限定。