本文介绍了当没有类范围处于活动状态时,无法访问self ::的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一个公共静态函数中使用PHP函数,如下所示(我已经缩短了一些东西):

I am trying to use a PHP function from within a public static function like so (I've shortened things a bit):

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".

如果我在 inside_this 函数之外调用 second_function / p>

If I call second_function outside of the inside_this function, it works fine:

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

我需要做什么才能在 inside_this 函数中使用 second_function

What do I need to do to be able to use second_function from within the inside_this function?

推荐答案

这是因为 PHP中的所有函数都具有全局范围 - 即使它们被定义,

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.

所以你必须这样做:

 function inside_this() {
   $some_var = MyClass::second_function();
 }

这篇关于当没有类范围处于活动状态时,无法访问self ::的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 04:46