I’m getting sort of an unexpected behaviour while trying to implement a class A that uses a class B. Here are the contents of the files:
> 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
Is there some PHP quirk I should have known about? Requiring B.php in test.php is ugly in this case and I’d prefer a better solution.
Replace
$b = new B();with:$this->b = new B();in yourAclass.See also that
require_onceis a statement, not a function. So you can use it without quotes.