Php 当没有类作用域处于活动状态时,无法访问self::
我正试图从一个公共静态函数中使用PHP函数,就像这样(我把事情缩短了一点): 这就是我得到错误“当没有类作用域处于活动状态时无法访问self::的时候” 如果我调用Php 当没有类作用域处于活动状态时,无法访问self::,php,class,object,scope,Php,Class,Object,Scope,我正试图从一个公共静态函数中使用PHP函数,就像这样(我把事情缩短了一点): 这就是我得到错误“当没有类作用域处于活动状态时无法访问self::的时候” 如果我调用second\u函数在该函数的内部,它可以正常工作: class MyClass { public static function first_function() { function inside_this() { // some stuff here }
second\u函数
在该函数的内部,它可以正常工作:
class MyClass {
public static function first_function() {
function inside_this() {
// some stuff here
}
$some_var = self::second_function(); // this works
} // End first_function
protected static function second_function() {
// do stuff
} // End second_function
} // End class PayPalDimesale
我需要做什么才能从这个
函数的内部使用第二个函数
?这是因为PHP中的所有函数都具有全局作用域——它们可以在函数外部调用,即使它们是在函数内部定义的,反之亦然
所以你必须做:
function inside_this() {
$some_var = MyClass::second_function();
}
使用PHP5.4:
<?php
class A
{
public static function f()
{
$inner = function()
{
self::g();
};
$inner();
}
private static function g()
{
echo "g\n";
}
}
A::f();
尝试将第一个函数更改为
public static function first_function() {
$function = function() {
$some_var = self::second_function(); // now will work
};
///To call the function do this
$function();
// other code here...
} // End first_function
你试过闭嘴吗<代码>函数中的函数使用($self){
我意识到self
不是一个变量太晚了……他的是受保护的
,而不是private
@Cole Johnson,private更具限制性,这就是我在示例中使用它的原因。@Matthew是否有任何文档说明为什么它在5.3版本的php中不起作用,并且在5.4版本中起作用version@aravind.udayashankara,我不确定是否明确提到了它,但在这里您将看到PHP5.4在闭包中引入了$this
:。不是同一件事,但它是相关的。@Matthew非常感谢您的帮助sharing@JohnRobinson这是因为该方法是受保护的。@xdazz,是否要将MyClass保存到变量中并将其传递给函数而不是将类名MyClass
硬编码到代码中?(否则,如果更改类名,则需要在整个文件中搜索并替换“MyClass”)
g
public static function first_function() {
$function = function() {
$some_var = self::second_function(); // now will work
};
///To call the function do this
$function();
// other code here...
} // End first_function