使用构造函数

时间:2016-05-08 06:11:30

标签: php oop

我是一名刚开始使用PHP的OOP的第二年IT学生,我真的很难掌握它,我已经用程序方式编写了多年,所以请理解转换OOP非常具有挑战性,而且我还没有看到它的好处,无论如何只需得到我的胸部。

问题 enter image description here enter image description here enter image description here enter image description here

根据上面的问题我上面的代码,我调整到无限,我的规定的书也不是很有帮助

CODE

class Registration{
        private $user_type;
        private $user_name;

        function __construct($user_type, $user_name){
            $this->user_type=$user_type;
            $this->user_name=$user_name;
        }//constructor

        function setUser($user_type, $user_name){
            if($user_type == "admin"){
                $user_name = "Peter";
                $msg = "Hi administrator ".$user_name;  
            }
            else if($user_type="member"){
                $user_name = "Ntubele123!";
                $msg = "Hi member ".$user_name; 
            }
        }//function

        function getUser(){
            return $this->user_type;
        }//function getter

}//class

    $userInfo = new Registration($user_type, $user_name);
        $user = $userInfo->setUser("admin", "Peter");
        $user = $userInfo->getUser();

我的问题

  • 我怀疑上面的代码有很多错误,如果有人能够让我知道我哪里出错了,我应该考虑改变,保持初学者友好,它非常感谢。

错误

未定义的变量user_type& USER_NAME

3 个答案:

答案 0 :(得分:1)

construct函数中设置属性时,在其他函数中使用参数并不是一个好习惯。在班级中全局使用属性

或者不是在construct函数中设置它,而是在每个函数中获取数据。

此外,如果您有大量与用户相关的数据,有时使用数组会更好。例如,当您有10个属性时,请尝试在数组中使用。

关于错误部分,您应该在实例化类之前将变量设置为特定值。

答案 1 :(得分:1)

$userInfo = new Registration($user_type, $user_name);

在这一行$user_type中,$user_name未定义,因为没有使用此名称声明的变量

首先声明变量,而不是创建Registration class

的对象

答案 2 :(得分:1)

在OOP代码中使用变量没有什么不同。在将它们用作参数之前,您仍然需要设置它们。所以它应该是:

$name = "Fred";
$type = "admin";
$user = new Registration($type, $name);

您的setter方法应该设置属性的值。所以它应该是:

function setUser($username) {
    $this->user_name = $username;
}

setter方法通常应该一次只设置一个属性。

全班应该如下:

class Registration{
    private $user_type;
    private $user_name;

    function __construct($user_type, $user_name){
        $this->user_type=$user_type;
        $this->user_name=$user_name;
    }//constructor

    function setUser($user_name){
        $this->user_name = $user_name;
    }

    function setType($type) {
        $this->user_type = $type;
    }

    function getUser(){
        return $this->user_name;
    }//function getter

    function getType() {
        return $this->user_type;
    }

    function greet() {
        echo "Hello " . $this->user_type . " " . $this->user_name;
    }

}//class

$user = new Registration("admin", "Joe");
$user->greet();