2015-08-14 35 views

回答

0

你有什么是无效的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来引用自己的属性。

+0

谢谢,这很有帮助。 –

+0

如果这解决了您的问题,请单击答案左侧的复选标记。 – Anonymous

2

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

?> 
相关问题