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するために使用することはできません。これは、実際のグローバル スコープのみを参照し、「親」スコープをまったく参照しないためです。例えば$thisglobal

$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 に答える