PHP-如何在第二个类的函数中从一个类运行函数?

PHP-如何在第二个类的函数中从一个类运行函数?,php,class,scope,Php,Class,Scope,这可能吗 class Foo { public function bar() { return true; } } class Foo2 { $fooey = new Foo; public function bar2() { if ( $fooey->bar ) { return 'bar is true'; } } } 我意识到上述方法行不通,因为我需要在bar2的范围内获得$fooey。我该怎么做 提前感谢。您不能在

这可能吗

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

class Foo2 {
  $fooey = new Foo;

  public function bar2() {
    if ( $fooey->bar ) {
        return 'bar is true';  
    }
  }
}
我意识到上述方法行不通,因为我需要在bar2的范围内获得$fooey。我该怎么做


提前感谢。

您不能在函数之外的类中创建对象,因此请使用
\u 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';  
    }
  }
}

?>

您拥有的不是有效的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
  • 您需要初始化构造函数中的内容(或将其作为变量传递)

  • 您需要使用
    $this
    来引用自己的属性


  • 谢谢,这很有帮助。如果这解决了您的问题,请单击答案左侧的复选标记。