duanni5726
2017-06-06 21:15
浏览 61
已采纳

甚至不能实例化类

I'm very new to PHP, and I can't solve an issue even I read a lot of tutorials and SO posts. I've a custom class (user), and I'd like to instantiate it in php code, but even I include it, I get this error.

Fatal error: Class 'User' not found in D:\wamp64\www\MyFirstPhp\formPhp.php on line 17

Please help me find out what I do wrong.

Here is my user class:

  <?php
/**
 * Created by IntelliJ IDEA.
 * User: molnard
 * Date: 2017. 06. 06.
 * Time: 15:36
 */

namespace infopro;


class User
{
    private $username;
    private $userage;
    private $sex;

    public function __construct($username, $userage, $sex)
    {
        if (!is_null($username)) $this->username = $username;
        if (!is_null($userage)) $this->userage = $this->userage;
        if (!is_null($sex)) $this->sex = $sex;
    }

    /**
     * @return mixed
     */
    public function getUsername()
    {
        return $this->username;
    }

    /**
     * @param mixed $username
     */
    public function setUsername($username)
    {
        $this->username = $username;
    }

    /**
     * @return mixed
     */
    public function getUserage()
    {
        return $this->userage;
    }

    /**
     * @param mixed $userage
     */
    public function setUserage($userage)
    {
        $this->userage = $userage;
    }

    /**
     * @return mixed
     */
    public function getSex()
    {
        return $this->sex;
    }

    /**
     * @param mixed $sex
     */
    public function setSex($sex)
    {
        $this->sex = $sex;
    }
}
?>

And here is my form.php class where I'd like to instantiate user class.

    <!Doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Form php</title>
</head>
<body>
<?php
include("User.php");

$name = $_POST["name"];
$age = $_POST["age"];
$sex = $_POST["sex"];
echo "New user<br>name: " . $name . "<br>" .
    "age: " . $age . "<br>" . "sex: " . $sex."<br>";

$newuser = new User($name, $age, $sex);
$newAge = $newuser->getAge();
echo $newAge;
?>
</body>
</html>
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

4条回答 默认 最新

  • dongleman4760 2017-06-06 21:32
    最佳回答

    The exception already told you, whats wrong with your code. There's no such User class. If you use namespaces, and your currently in another namespace (or no namespace), you have to use fully qualified names. Means: namespace + classname.

    In your case, you have to prefix your class name with the namespace infopro, which leads to \infopro\User

    $user = new \infopro\User(...);
    

    If you don't want to use always the fqn and you are in a diffrent namespace, you could also import the classname into the local scope of the file with use.

    use \infopro\User;
    
    // somewhere later ...
    $user = new User(...);
    
    评论
    解决 无用
    打赏 举报
查看更多回答(3条)

相关推荐 更多相似问题