在类定义之外访问变量和方法
问题描述:
假设我有以下几行的php文件:
Suppose I have a php file along these lines:
<?php
function abc() { }
$foo = 'bar';
class SomeClass { }
?>
在SomeClass
中使用abc()
和$foo
时,我需要做些特别的事情吗?我正在考虑在函数中使用global
来访问在函数外部定义的变量的方法.
Is there anything special I have to do to use abc()
and $foo
inside SomeClass
? I'm thinking along the lines of using global
in a function to access variables defined outside the function.
(我是PHP中OOP的新手)
(I'm new to OOP in PHP)
答
任何类之外的函数都是全局函数,可以从任何地方调用.变量也一样..只是记得要使用全局变量...
functions outside any class are global an can be called from anywhere. The same with variables.. just remember to use the global for the variables...
例如
<?php
function abc() { }
$foo = 'bar';
class SomeClass {
public function tada(){
global $foo;
abc();
echo 'foo and '.$foo;
}
}
?>