我在嘗試實現一個使用B類的類A時出現了某種意想不到的行爲。下面是這些文件的內容:PHP 5.4.4-9(debian測試) - require_once不遞歸拉文件
> cat test.php
<?php
error_reporting(E_ALL);
require_once("A.php");
//require_once("B.php"); //now it'd work, but it's not the point
$a = new A();
$b = $a->getB();
var_dump($b);
$b->sayHi();
> cat A.php
<?php
require_once('B.php');
class A
{
private $b;
public function getB()
{
return $this->b;
}
public function __construct()
{
$b = new B();
}
}
> cat B.php
<?php
class B
{
public function sayHi()
{
echo "Hi!";
}
}
> php test.php
NULL
PHP Fatal error: Call to a member function sayHi() on a non-object in /var/www/przypadek_testowy/test.php on line 10
是否有一些我應該知道的PHP怪癖?在這種情況下,在test.php中需要B.php是醜陋的,我更喜歡更好的解決方案。
'$ b = new B();'你的意思是'$ this-> b'吧? – Leigh
正如所評論的,問題出在您的代碼上。無論如何,無論你在哪裏使用'require'都是醜陋的。如果可能的話,切換到自動加載:http://php.net/manual/en/language.oop5.autoload.php – jeroen
感謝您的答案!這絕對值得我爲之付出的分數。 – d33tah