php - 使用对象运算符循环

标签 php mysql loops calendar operators

我正在玩弄 PHP Calendar (Corey Worrell) 并且有一个关于实例循环的问题。为了初始化日历,我必须输出这个:

$calendar->standard('today')
        ->standard('prev-next')
        ->standard('holidays')
        ->attach($event1)
        ->attach($event2)
        ->attach($event3)
        ->attach($event4)
        ->attach($event5)
        ->attach($event6)
        ->attach($event7)
        ->attach($event8)
        ->attach($event9)
        ->attach($event10)
        ->attach($event11)
        ->attach($event12)
        ->attach($event13)
        ->attach($event14)
        ->attach($event15)
        ->attach($event16)
        ->attach($event17);

每个->attach($event#) 在日历上输出一个事件。我想遍历这些数字递增的事件名称,但是在该代码中的任何位置添加 for 循环会破坏所有内容,并输出此错误:

PHP Catchable fatal error: Argument 1 passed to Event_Subject::attach() must be an instance of Event_Observer, null given, called in /calendar/index.php on line 75 and defined in /calendar/classes/event_subject.php on line 21

这是我试过的循环:

$calendar->standard('today')
        ->standard('prev-next')
        ->standard('holidays')
        for ($inc = 0; $inc <= $number_of_events; $inc++) {
            if ($inc == $number_of_events) {
                ->attach($$event_name);
            }
            else {
                ->attach($$event_name)
            }
        }

我怎样才能在这里循环?我的事件存储在 MySQL 中,我正在执行 $number_of_events = $result->num_rows 以确定返回的事件数。 ->attach($event#) 会循环,重复直到达到总的 $number_of_events

最佳答案

这就是所谓的方法链。类的每个方法都通过$this 返回被调用对象的一个​​实例,允许您堆叠方法调用。方法链接是可能的,因为该函数返回对您的对象的引用。

因为支持方法链的类中的每个函数都返回调用对象,您只需将返回的对象重新赋值回原来的$calander变量即可;

 for ($inc = 0; $inc <= $number_of_events; $inc++) {
        if ($inc == $number_of_events) {
            $calander = $calander->attach($event1);
        }
        else {
            $calander = $calander->attach($event1);
        }
    }

此外,如果您想遍历变量名,可以在循环中使用变量;

$variable = "event".$inc;

$calander = $calander->attach($$variable);

所以这将变成 $event0, $event1, $event2

关于php - 使用对象运算符循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32054158/

相关文章:

php - 将搜索请求从我的网站转移到另一个网站

Python 'timestamp' 无法转换为MySQL类型

mysql - MYSQL 中数据实际存储在哪里(innodb)?

c++ - 如何在 C++ 中使用 for 循环递增两个不同的值

python - 使用相同的索引并行遍历 2 个列表

javascript - 需要一些帮助来解决这个循环

php - 我可以向 Android Studio 中的现有项目添加新包吗?

php - 500 内部服务器 Joomla

php - Wordpress 自定义 single-product.php : how is <a data-full=. .. 更改主图像?

sql - 在没有子查询的 MySQL 中,优先于 GROUP BY 的 ORDER BY