从类中的函数调用函数

时间:2016-10-07 07:36:57

标签: php function

我有这个PHP代码,我想从function firstnameLength()拨打class formular_validiation

class formular_validiation
{
    private static $minLength = 2;
    private static $maxLength = 250;
    public static function firstname() {

        function firstnameLength($firstnameLength){
            if ($firstnameLength < self::$minLength){

            }
            elseif ($firstnameLength > self::$maxLength) {

            }
        }

        function firstnameNoSpace($firstnameNoSpace) {
            preg_replace(" ", "", $firstnameNoSpace);
        }

    }
}

我想说的是:

formular_validiation::firstname()::firstnamelength()

但这是错误的。

1 个答案:

答案 0 :(得分:1)

您正在寻找的是method chaining,但如果您想静态调用第一种方法,则应执行以下操作:

class FormularValidation
{
    private $minLength = 2;
    private $maxLength = 250;
    private $firstname;

    public function __construct($firstname)
    {
        $this->firstname = $firstname;
    }

    public static function firstname($firstname) {
        return new self($firstname);
    }

    public function firstnameLength()
    {
        $firstnameLength = strlen($this->firstname);

        if ($firstnameLength < $this->minLength){
            return 'something';
        }
        elseif ($firstnameLength > $this->maxLength) {
            return 'something else';
        }
    }

    public function firstnameNoSpace()
    {
         return preg_replace(" ", "", $this->firstname);
    }
}

用法:

$firstnameLength = FormularValidation::firstname('Mihai')->firstnameLength();