PHP OOP - 将对象传递给函数不起作用

时间:2014-11-27 13:41:06

标签: php oop php-5.5

我在PHP OOP上遇到了问题。我尝试做一些我一直在.NET中做的事情 - 将整个对象传递给函数。不幸的是,脚本似乎不起作用,当我尝试调试(使用Netbeans)时它停在这里:

$ud = new userdetails($fullname, $email, $contact, $username, $password, $password2); 

有人可以告诉我,我做错了什么吗?提前谢谢!

我的剧本:

<?php
include 'class/registration.php';

$fullname = $_POST['fullname'];
$email = $_POST['email'];
$contact = $_POST['contact'];
$username = $_POST['username']; 
$password = $_POST['password'];
$password2 = $_POST['password2'];

$ud = new userdetails($fullname, $email, $contact, $username, $password, $password2);

if (registration::checkEmptyField($ud)==true){
        $error = "Please don't leave any field empty";
    } 

userdetail class:

<?php
class userdetails {

protected $_fullname;
protected $_email; 
protected $_contact; 
protected $_username;   
protected $_password; 
protected $_password2;

public function __construct($fullname,$email,$contact,$username,$password,$password2) {   
    $this->_fullname = $fullname;    
    $this->_email = $email;  
    $this->_contact = $contact;  
    $this->_username = $username;  
    $this->_password = $password;  
    $this->_password2 = $password2;  
}    

public function get_fullname() {    
    return $this->_fullname;          
}     

public function get_email() {    
    return $this->_email;          
}  

public function get_contact() {    
    return $this->_contact;          
}  

public function get_username() {    
    return $this->_username;          
}  

public function get_password() {    
    return $this->_password;          
}  

public function get_password2() {    
    return $this->_password2;          
}  

}

注册类:

<?php
class registration {

 function checkEmptyField(&$userdetails){   

     if ($userdetails-> get_fullname == ''){
         return true;
     }       
     elseif ($userdetails->get_email == ''){
         return true;
     }    
     elseif ($userdetails->get_contact == ''){
         return true;
     }    
     elseif ($userdetails->get_username == ''){
         return true;
     }    
     elseif ($userdetails->get_password == ''){
         return true;
     }    
     elseif ($userdetails->get_password2 == ''){
         return true;
     }

   }

 }

2 个答案:

答案 0 :(得分:3)

你要求财产,而不是这里的方法:$userdetails-> get_fullname

正确方式:$userdetails-> get_fullname()

您应该始终打开错误报告,因为这应该由php报告。

答案 1 :(得分:0)

您致电registration::checkEmptyField()的方式要求将其声明为static

<?php
class registration {

    static function checkEmptyField(userdetails $userdetails) {
       ...
    }
}

没有必要在$userdetails前加&,在PHP中,对象总是通过引用传递。最好使用类型提示:将参数名称($userdetails)添加到其预期类型(在这种情况下为类userdetails)。