从抽象父类php取消设置子对象静态变量

时间:2014-12-03 11:10:25

标签: php laravel abstract-class static-variables late-static-binding

我正在使用Laravel,它是验证者。

我的控制器中有以下代码:

class ResellerController extends BaseController{

    public function add() {

        //some code before

        $userValidator =  new App\Services\Validators\UserCreateValidator();
        //HERE I WANT TO REMOVE THE company KEY FROM THE RULES IN THE USERS CREATE VALIDATOR
        $userValidator->removeRule('company');      

        //code execution continues      
    }
}

UserCreateValidator扩展父Validator类:

namespace App\Services\Validators;

class UserCreateValidator extends Validator {

    public static $rules = array(
        'firstName' => 'required',
        'lastName' => 'required',
        'email' => 'required|email|unique:users',
        'company' => 'required'
    );  
}

这是基本的Validator类:

namespace App\Services\Validators;

abstract class Validator {

    /**
     * Validation rules
     * @var array
     */
    public static $rules;

    //THIS CODE DOES NOT WORK IN THE CONTROLLER UP
    public static function removeRule($ruleKey){

        if(is_array($ruleKey))
        {
            foreach($ruleKey as $key)
            {
                if(!array_key_exists($key, static::$rules)) continue;

                unset(static::$rules[$key]);
            }

            return true;
        }

        if(!array_key_exists($ruleKey, static::$rules)) //return false;

        unset(static::$rules['company']);

        return true;
    }
}

static::$rules[$key]ResellerController的取消设置不起作用。

我可以在 XDEBUG 会话中看到(在执行此行之后),static::$rules['company']仍然存在于UserCreateValidator属性中。

我认为 Late Static Binding 应该解决这个问题? 有什么问题?

1 个答案:

答案 0 :(得分:0)

问题解决了。它位于以下评论部分:

if(!array_key_exists($ruleKey, static::$rules)) //return false;

取消注释return false后,取消设置工作正常。

愚蠢的错误:)