[英]Cannot access self:: when no class scope is active
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". 那是我收到错误“无法访问自我::当没有类活动范围时”。
If I call second_function
outside of the inside_this
function, it works fine: 如果我在
inside_this
函数之外调用second_function
,它可以正常工作:
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_function
from within the inside_this
function? 为了能够在
inside_this
函数中使用second_function
,我需要做什么?
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();
}
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
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.