php 5.3+
很抱歉这个问题很长,但我想完全了解这一点.
我知道我不能从静态方法中调用非静态相同类方法,而不将类实例化为对象.
class Person
{
private $people_array;
function data_all_get()
{ // touch database, return array of people
$this->people_array = // etc dbquery results
}
static function showPeople()
{ // call class method
$people_data = $this->data_all_get();
// Fatal error: Using $this when not in object context
}
} // end class Person
Run Code Online (Sandbox Code Playgroud)
从搜索SO,我发现了一些有趣的方法,但想知道每种方法如何影响代码环境.
我的问题如下:
我可以将类实例化为静态方法中的对象,以获得对非静态方法的访问
static function showPeople()
{ // instantiate as object
$person = New Person();
// call class method
$people_data = $this->data_all_get();
}
Run Code Online (Sandbox Code Playgroud)
Q1 - 这会导致什么问题? 在我的情况下,该类没有构造函数,因此该实例不会影响其他类方法或变量.在脚本执行期间,这个新对象会占用内存中的一小块空间吗?似乎不太糟糕...... …