dsz90288 2014-06-30 17:38
浏览 31
已采纳

PHP类在构造函数中分配属性

<?php 
$login1 = new Login("cam", "1234"); echo "<br>";
echo $login1->authenticate($login1->name, $login1->this->password);

class Login{
     public $name;
     public $password;

    function Login($u, $w){
        $this->name = $u;
        $this->$password = $w;
    }

    function authenticate($name, $password){
        $lookupusername = "cam"; 
        $lookuppassword = "1234";
        if($name == $lookupusername && $password == $lookuppassword){
            return "Login Success";
            echo "Login Success";
        }   else {
                return "Login Fail";
                echo "Login Fail";
            }
    }
}
?>

I am new to PHP. I am wondering why the constructor in my login class is not setting the string literals as the name and password properties of the class. I tried a set() method and that didn't work either. I also tried assigning the string literals as variables and passing them in by reference. Nope. Where am I going wrong?

  • 写回答

1条回答 默认 最新

  • dongyu9263 2014-06-30 17:42
    关注

    PHP doesn't build a constructor in the same way that Java does (which is what your example appears to be based on). You'll want to use PHP's __construct method, like below:

    public function __construct($u, $w) {
        $this->name = $u;
        $this->password = $w;
    }
    

    Also, your way of accessing the name attribute is correct, but password is incorrect. Use $this->password instead of $this->$password, and $login1->password instead of $login1->this->password

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计