Php 在嵌套函数中使用$this错误
我尝试在类中的嵌套函数中使用$this 我使用以下命令调用该方法:Php 在嵌套函数中使用$this错误,php,function,nested,this,Php,Function,Nested,This,我尝试在类中的嵌套函数中使用$this 我使用以下命令调用该方法: $check_membership = $this->setAuthorisation($posted_username, $ldap_connection); 该方法如下所示: private function setAuthorisation($posted_username, $ldap_connection) { // split the posted username for filtering com
$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吗?外部函数在我的类中。您的嵌套函数就是。。。函数。它不是父类的方法,即使它只存在于该方法中。您可以将外部
$this
作为参数传入,例如
class foo {
function bar() {
function baz($qux) {
...
}
baz($this);
}
}
但是。。。无论如何,你不应该像那样嵌套函数。为什么不将嵌套函数升级为完整的“常规”函数,这意味着它将是类的一个方法,然后$this
将按预期提供
另一个注意事项是,您不能使用$global
使$this
在方法内部可见,因为global
只查看真正的全局范围,而根本不查看“父”范围。e、 g
$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
,为什么要这样嵌套函数?只需将setMembershipUser()
创建为private
的“普通”函数。很长时间没有在类中看到这样的嵌套,它们在类中被称为方法
,尽管看起来更像structured@GordonM是的,嵌套函数有(一些,很少)原因,但在这种情况下,它们的意义是什么?