0

我尝试在班级的嵌套函数中使用 $this。

我用以下方法调用该方法:

$check_membership = $this->setAuthorisation($posted_username, $ldap_connection);

该方法如下所示:

private function setAuthorisation($posted_username, $ldap_connection)
{
    // split the posted username for filtering common name
    $temp_var = explode('\\', $posted_username);
    $cn_name = end($temp_var);

    // filter parameter for ldap_search
    $filter = "objectClass=*";

    // search attribute to get only member
    $attr = array("member");

    // possible membership status:
    // group_membership: "null": No access to enter the page.
    // group_membership:    "1": Access to the page, but no admin rights.
    // group_membership:    "2": Access to the page with admin rights.

    /**
     * perform the setMembershipUser for authorisation the "user" group
     */
    function setMembershipUser($ldap_connection, $cn_name, $filter, $attr)
    {
        // search for user in the authorized ad group "user"
        $user_result = ldap_search($ldap_connection, GROUP_USER.",".BASE_DS, $filter, $attr);

        // reads multiple entries from the given result
        $user_entries = ldap_get_entries($ldap_connection, $user_result);

        // check if cn_name is in $user_entries
        if (preg_grep("/CN=".$cn_name."/i", $user_entries[0]["member"]))
        {
            $this->group_membership = 1;
        } 
        else 
        {
            $this->group_membership = null;
        }
    }
    setMembershipUser($ldap_connection, $cn_name, $filter, $attr);
    return $this->group_membership;
}

在函数 setMembershipUser 中出现错误“致命错误:不在对象上下文中使用 $this...”

我可以在嵌套函数中使用 $this 吗?外部函数在我的课堂上。

4

1 回答 1

1

您的嵌套函数就是……一个函数。它不是父类的方法,即使它只存在于该方法中。您可以将外部$this作为参数传递,例如

class foo {
   function bar() {
       function baz($qux) {
          ...
       }
       baz($this);
   }
}

但是......无论如何,你不应该嵌套这样的函数。为什么不将您的嵌套函数提升为成熟的“常规”函数,这意味着它将成为您的类的方法,然后$this可以按预期使用。

另请注意,您不能使用$global使$this方法内部可见,因为global只查看真正的全局范围,它根本不查看“父”范围。例如

$x = 42;
class foo {
   function bar() {
       $x = 13;
       function baz() {
            $x = 69;
            echo $x; // outputs 69
            global $x;
            echo $x; // outputs 42
       }
   }
}

baz() 函数无法获得 $x = 13,因为在 PHP 中任何地方可用的唯一范围是“本地”范围,即69定义的,和全局范围,其中 $x 是42

于 2013-09-23T15:03:27.847 回答