【问题标题】:PHP - How to run a function from one class inside a function in a second class? [duplicate]PHP - 如何在第二个类的函数中从一个类运行一个函数? [复制]
【发布时间】:2015-11-08 06:06:22
【问题描述】:

这可能吗?

class Foo {
  public function bar() {
   return true;
  }
}

class Foo2 {
  $fooey = new Foo;

  public function bar2() {
    if ( $fooey->bar ) {
        return 'bar is true';  
    }
  }
}

我意识到上述方法行不通,因为我需要在 bar2 的范围内获取 $fooey。我该怎么做?

提前致谢。

【问题讨论】:

    标签: php class scope


    【解决方案1】:

    您不能在函数之外的类中创建对象,因此请使用__construct,因为它会在创建对象时首先运行。

    <?php
    
    class Foo {
      public function bar() {
       return true;
      }
    }
    
    class Foo2 {
      private $fooey = null
    
    public __construct() {
        $this->fooey = new Foo();
    }
    
      public function bar2() {
        if ( $this->fooey->bar ) {
            return 'bar is true';  
        }
      }
    }
    
    ?>
    

    【讨论】:

      【解决方案2】:

      您所拥有的不是有效的 PHP 语法。我相信您正在寻找这样的东西:

      class Foo {
        public function bar() {
         return true;
        }
      }
      
      class Foo2 {
          private $fooey;
          public function __construct() {
            $this->fooey = new Foo;
          }
      
        public function bar2() {
          if ( $this->fooey->bar() ) {
              return 'bar is true';  
          }
        }
      }
      
      $obj = new Foo2;
      $obj->bar2(); // 'bar is true' will be printed
      
      1. 你需要在构造函数中初始化东西(或者作为变量传入)。

      2. 你需要使用$this来引用自己的属性。

      【讨论】:

      • 谢谢,很有帮助。
      • 如果这解决了您的问题,请点击答案左侧的复选标记。
      猜你喜欢
      • 2016-05-02
      • 2019-08-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-15
      相关资源
      最近更新 更多