php 无法访问 self:: 当没有类作用域处于活动状态时
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11255095/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cannot access self:: when no class scope is active
提问by JROB
I am trying to use a PHP function from within a public static function like so (I've shortened things a bit):
我试图在像这样的公共静态函数中使用 PHP 函数(我已经缩短了一些东西):
class MyClass {
public static function first_function() {
function inside_this() {
$some_var = self::second_function(); // doesnt work inside this function
}
// other code here...
} // End first_function
protected static function second_function() {
// do stuff
} // End second_function
} // End class PayPalDimesale
That's when I get the error "Cannot access self:: when no class scope is active".
那是我收到错误“无法访问 self:: when no class scope is active”的时候。
If I call second_functionoutside of the inside_thisfunction, it works fine:
如果我second_function在inside_this函数之外调用,它工作正常:
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
What do I need to do to be able to use second_functionfrom within the inside_thisfunction?
我需要做什么才能second_function在inside_this函数中使用?
回答by xdazz
That is because All functions in PHP have the global scope- they can be called outside a function even if they were defined inside and vice versa.
这是因为PHP 中的所有函数都具有全局作用域- 即使它们是在函数内部定义的,它们也可以在函数外部调用,反之亦然。
So you have to do:
所以你必须这样做:
function inside_this() {
$some_var = MyClass::second_function();
}
回答by Matthew
Works with PHP 5.4:
适用于 PHP 5.4:
<?php
class A
{
public static function f()
{
$inner = function()
{
self::g();
};
$inner();
}
private static function g()
{
echo "g\n";
}
}
A::f();
Output:
输出:
g
回答by Kris
Try changing your first function to
尝试将您的第一个函数更改为
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

