我有一个公共对象让我们说X.在配置文件中定义。我如何在类中的方法中使用此对象。我认为当我在该方法中全局化X时,它会在类中看起来。 :(
include('config.php'); //the objec X is defined here
class MyClass{
public foo(){
global $X; // I thing It is looking within the class
}
}
答案 0 :(得分:1)
我做了一个演示......我希望这是你想要的...... global.php
<?php
$x=5;
?>
的index.php
<?php
include('global.php');
class foo{
private $value;
function __construct(){
global $x;
$this->value=$x;
}
function show(){
return $this->value;
}
}
$a= new foo();
echo $a->show();
?>
答案 1 :(得分:0)
这对我有用:
class LemonSalesman {
public function advertise() {
echo 'Get your fresh lemons here!';
}
}
$LemonSalesman = new LemonSalesman();
class MyObject {
public function foo() {
global $LemonSalesman;
$LemonSalesman->advertise();
}
}
$MyObject = new MyObject();
$MyObject->foo();
你确定你的$ X对象是全局的吗?
答案 2 :(得分:0)
如果您以这种方式在配置文件中定义$x
:
<?php
$x = 'somevalue';
?>
然后在函数中使用global
就可以了。或者你也可以使用全局数组来访问变量$GLOBALS['x']
,但是我不确定它有多常见或建议。
但是,如果您在函数或类中定义了配置变量,那么它也必须具有全局,例如:
<?php
function loadConfig(){
// no global here means that $x is not global.
$x = 'somevalue';
}
<?