php - 将日期从字符串转换为 PDO 中的对象

标签 php mysql date pdo

我正在学习这门 PHP 类(class),但我真的迷失了这一点。重点是能够使用类来操纵日期。

<?php
    ini_set('display_errors', 'On');

    // Create a class called user

    class User {

        protected $dates = [
            'created',
        ];
        // This is supposed to convert my dates from a string to an object
        public function __construct() {
            foreach($this->$dates AS $date) {
                $property = $this->{$date};
                $this->{$date} = new DateTime($property);
            }
        }
        // Adding a public function that will be available outsite of the class
        public function getFullName() {
            return "{$this->firstname} {$this->lastname}";
        }
    }

    $db = new PDO('mysql:host=127.0.0.1;dbname=pdo', 'root', '');

    $req = $db->query("SELECT * FROM users");
    $req->setFetchMode(PDO::FETCH_CLASS, 'User');

    echo '<pre>', var_dump($req->fetch()), '</pre>';
    die();

?>

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>PDO</title>
    </head>
    <body>
        <?php while($user = $req->fetch()): ?>
            <div class="user">
                <h4><?php echo $user->getFullName(); ?></h4>
                <p>Registered on <?php echo $user->created->format('d M Y'); ?></p> <!-- does not work -->
            </div>
        <?php endwhile; ?>
    </body>
</html>

当我加载我的页面时,出现三个错误:

Notice: Undefined variable: dates in /Applications/XAMPP/xamppfiles/htdocs/Side-Projects/Courses/PHP:SQL/Learn PHP Programming From Scratch/04 - PHP Data Object (PDO)/51 - User class date/index.php on line 13

Notice: Undefined property: User::$ in /Applications/XAMPP/xamppfiles/htdocs/Side-Projects/Courses/PHP:SQL/Learn PHP Programming From Scratch/04 - PHP Data Object (PDO)/51 - User class date/index.php on line 13

Warning: Invalid argument supplied for foreach() in /Applications/XAMPP/xamppfiles/htdocs/Side-Projects/Courses/PHP:SQL/Learn PHP Programming From Scratch/04 - PHP Data Object (PDO)/51 - User class date/index.php on line 13

有人可以帮助我了解如何解决这个问题吗?提前谢谢你:)

最佳答案

foreach($this->$dates AS $date)

应该是

foreach($this->dates AS $date)

否则,您将尝试将 $dates 用作可变变量

关于php - 将日期从字符串转换为 PDO 中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48498485/

相关文章:

Java Date 对象显示 future 的时间

javascript - 如何将变量作为属性从 php 传递到 javascript?

php - 1 秒内根据多个请求更新 Mysql

mysql - 保存时间大于24小时

AngularJS 更改日期格式(六月,星期三)从 Wed Jun 08 2016 05 :30:00 GMT+0530 (India Standard Time)

java - 带 am/pm 的日期对象的格式

php - 更改 auth_redirect() 页面

php - Javascript 无法解释返回的 xml

Mysql加入join子查询计数

javascript - 使用javascript自动计算具有来自mysql的数据的表行