【问题标题】:function in class, run only if variable is not set, PHP类中的函数,仅在未设置变量时运行,PHP
【发布时间】:2017-04-28 09:02:04
【问题描述】:

我想在课堂上写函数。我只想在未设置一个变量的情况下运行此函数。 我对此有 3 个想法,但我不知道哪个最好并且看起来“更专业”。

1:

if (!isset($this->variable) {
     $this->functionXxx();
}

2:

private function functionXxx()
{
     if (!isset($this->variable)) {
         //code here
     } 
}

3:

private function functionXxx()
{
     if (isset($this->variable)) {
         return;
     } 
     //code here
}

【问题讨论】:

  • 选择 2 个选项。
  • 这里的1选项是什么?你在课堂外使用$this 吗?顺便说一句:3 优于 2,因为您必须将所有代码包装在 if 中的 2 中,但 3 被称为 early return 行为,其余代码位于 @ 之外987654332@,表示函数返回nullvoid就可以了。
  • 选项 1 在课堂内。这意味着如果变量 isset 则不调用方法。

标签: php function return


【解决方案1】:

首先你应该停止调用methods 函数。

其次,如果methodXxx在操作后返回一些东西,你可以使用第三个选项,但如果methodXxx是我们所说的void函数(什么都不返回),那么你应该使用第二个选项。

【讨论】:

    猜你喜欢
    • 2012-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-14
    相关资源
    最近更新 更多