我正在学习这门 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/