创建静态方法并在 PHP 中调用该方法


Creating staitic method and calling the method in PHP

我通过创建对象从表单类中获取值。它工作正常。但我想使用静态方法做到这一点。我尝试过但没有成功。

public function display()
{
    $newform=new Form();
    echo "<pre>";
    var_dump($newform->getAll());
    var_dump($newform->get('name'));
}
<?php 
class Form
{
    private $value = array();
    function __construct() {
        // here you can use some validation or escapes 
        foreach($_POST as $key=>$value)
            $this->value[$key] = $value;
    }
    public function getAll() {
        return $this->value;
    }
    public function get($value) {
        $this->value = $_POST[$value];
        return $this->value;
    }
}

也许你应该尝试阅读有关静态关键字的PHP文档?

例:

class Form {
    private static $value = array();
    public static function factory() {
        // here you can use some validation or escapes 
        foreach($_POST as $key => $value) {
            static::$value[$key] = $value;
        }
    }
    public static function getAll() {
        return static::$value;
    }
    public static function get($key) {
        return static::$value[$key];
    }
}

用:

public function display() {
    Form::factory();
    echo "<pre>";
    var_dump(Form::getAll());
    var_dump(Form::get('name'));
    echo "</pre>";
}

您不会在类外部将函数声明为公共/私有/受保护

你想静态调用这个方法,你可以尝试一下

<?php
     function display()
{
    $newform=new Form($_POST);
    echo "<pre>";
    var_dump(Form::getAll());
    var_dump(Form::get('name'));
}
class Form
{
private static $value = array();
function __construct(){
// here you can use some validation or escapes 
function __constract($array){
    foreach($array as $key=>$value)
        self::$value[$key] = $value;
    }
}
public static function getAll(){
    return self::$value;
}
public static function get($value){
        self::$value = self::$value[$value];
    return self::$value;
}
}

下面是getAll方法的示例。对于get方法,同样的想法:

public function display()
{
    var_dump(Form::getAll());
}
class Form
{
    private static $value = array();
   public static function initPost()
    {
        foreach($_POST as $key=>$value)
        self::$value[$key] = $value;
    }
    public static function getAll()
    {
        return self::$value;
    } 
}