2013-03-09 36 views
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","[email protected]"); 
$userDAO = new UserDAO(); 
$userDAO->insertUser($user); ?> 

返回的错误是

PHP开捕致命错误:参数1传递给用户:: getEmail()必须是,没有给出

+0

看看行号...'公共职能getEmail(字符串$电子邮件)'需要一个参数,我会让它'公共函数getEmail(){' – Wrikken 2013-03-09 00:06:40

+0

请注意[手册]中的注释(http://php.net/manual/en/language.oop5.typehinting。 PHP)虽然:_“类型提示不能使用具有诸如int或string之类的标量类型。 “_所以,除非你有'String'类,否则放弃这些​​提示。 – Wrikken 2013-03-09 00:08:34

回答

0

String的实例中删除您随时随地type hinting类型提示是字符串。字符串不能用于类型提示。 Int也一样。

1

PHP与JavaScripts typeof函数非常相似,它的名称为gettype

从PHP文档网站:

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

Info about this function can be found here.


使用此功能,您可以核对你的函数,如果返回的“字符串”类型,或任何其它数据类型你希望。

由于(string)不是PHP对象,你不能检查,如果它是一个字符串的实例,除非您创建用于该目的,这是很容易定制String Class/Object


从PHP文档网站 gettype

基本例如:

这个例子的
$data = array(1, 1., NULL, new stdClass, 'foo'); 

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

例子输出为:

integer 
double 
NULL 
object 
string 
相关问题