有什么方法可以使我的变量不可变,以便可以在foreach
中的任何地方调用具有相同变量名的类实例吗?
我在$user->count()
之后调用foreach
,但$user
修改了foreach
变量,并引发了一些错误:
致命错误:未捕获错误:调用C:\ xampp \ htdocs \ public_html \ test.php:48中未定义的方法stdClass :: count()堆栈跟踪:#0 {main}抛出于C:\ xampp \ htdocs \ public_html \ test.php,第48行
实现如下:
<?php
include 'connection.php';
class Collection {
public $items;
public function __construct ($items = []) {
$this->items = $items;
}
public function get() {
$object = $this->items;
return $object;
}
public function count() {
return count($this->items);
}
}
class User extends Collection {
}
class Post extends Collection {
}
$stmt = $connect->prepare("SELECT * FROM users_account");
$stmt->execute();
$row = $stmt->fetchAll(PDO::FETCH_OBJ);
$user = new User($row);
$users = $user->get();
$stmt = $connect->prepare("SELECT * FROM posts");
$stmt->execute();
$row = $stmt->fetchAll(PDO::FETCH_OBJ);
$post = new Post($row);
$posts = $post->get();
foreach ($users as $user) {
echo $user->username.'<br />';
}
echo $user->count();
echo "<hr />";
foreach ($posts as $post) {
echo $post->body.'<br />';
}
echo $post->count();
答案 0 :(得分:3)
为什么不简单地使用其他变量名?这是一个容易得多的解决方案,可以使代码更具可读性。
class Collection
{
protected $items; // protected because having strong encapsulation is good
public function __construct($items = [])
{
$this->items = $items;
}
public function get()
{
return $this->items; // no need to put it in a separate variable if you're simply returning
}
public function count()
{
return count($this->items);
}
}
class User extends Collection {}
// blah blah blah
$users = new User($row);
$userList = $users->get();
foreach ($userList as $user) {
// do work
}