0

我想使用 FILTER_VALIDADE_EMAIL 但它给了我一个警告说它需要一个字符串。我是 php 新手,我在尝试使用 OO 时遇到了麻烦。

<?php

Class User {

    private $id;
    private $login_name;
    private $hashed_password;
    private $email;


    public function __construct($login_name, $email){
        $this->login_name = $login_name;
        $this->email = $email;
    }

    public function getLoginName(){
        return $this->login_name;
    }

    public function setLoginName(String $login_name){
        $this->login_name = $login_name;
    }

    public function setEmail(String $email){
        $this->email = $email;
    }

    public function getEmail(String $email){
        return (string) $this->email;
    }
}?>


<?php

include("../lib/php/User.php");

class UserDAO {

    private $user;

    public function __construct(){
    }

    public function getUser(){
        return $this->user;
    }

    public function setUser(User $user){
        $this->user = $user;
    }


    public function insertUser(User $user){
        $email = $user->getEmail();
        $login_name = $user->getLoginName();
        //ver http://www.php.net/manual/en/function.filter-var.php
        if(filter_var($email, FILTER_VALIDATE_EMAIL) && empty($login_name)){
            echo "valid user";
        }
    }
}

$user = new User("user","user@gmail.com");
$userDAO = new UserDAO();
$userDAO->insertUser($user); ?>

返回的错误是

PHP Catchable 致命错误:传递给 User::getEmail() 的参数 1 必须是 String 的实例,没有给出

4

2 回答 2

1

PHP has something quite similar to JavaScripts typeof function, and it's named gettype.

From PHP docs site:

Returns the type of the PHP variable var. For type checking, use is_* functions.

Info about this function can be found here.


Using this function you can check against your function, if it returns the type of "string", or any other data type you wish.

Since (string) is not an object in PHP, you cannot check if it is an instance of a string, unless you create a custom String Class/Object for that purpose, which is quite easy.


Basic example of gettype from PHP docs site:

$data = array(1, 1., NULL, new stdClass, 'foo');

foreach ($data as $value) {
    echo gettype($value), "\n";
}

Example output of this example would be:

integer
double
NULL
object
string
于 2013-03-09T00:09:38.383 回答
0

Remove your type hinting anywhere the type hint is String. String cannot be used in type hinting. Same goes for Int.

于 2013-03-09T00:08:22.110 回答