Fatal error: Call to a member function add() on null
Fatal error: Call to a member function add() on null
我在我的项目中使用 League Container 包作为 DI。
class App extends Container {};
以上代码有效 fine.but 每当在我的应用程序中使用构造函数时都会触发问题 class。
class 应用扩展容器
{
public __construct(){};
}
它显示像-
致命错误:在 null
上调用成员函数 add()
我想知道在 oop 编程中它会导致什么
您在 "public" 之后缺少 "function"。
它不起作用的原因有几个:
public __construct(){};
不是定义 class 构造的正确方法。
如果这只是一个拼写错误,您将得到的实际错误是:
Fatal error: Call to a member function getDefinition() on a non-object
in ...
这是因为如果你扩展一个有结构的 class,那么你必须调用父结构,否则它将被丢弃。 (which it does).
所以在这里将它们 2 点放在一起是一个有效的例子:
<?php
// require 'vendor/autoload.php';
use League\Container\Container;
class App extends Container {
public function __construct() {
parent::__construct();
}
}
class Foo {
}
$container = new App;
// add foo to the container
$container->add('foo', 'Foo');
// retrieve foo from the container
$service = $container->get('foo');
var_dump($service instanceof Foo); // true
我在我的项目中使用 League Container 包作为 DI。
class App extends Container {};
以上代码有效 fine.but 每当在我的应用程序中使用构造函数时都会触发问题 class。 class 应用扩展容器
{
public __construct(){};
}
它显示像- 致命错误:在 null
上调用成员函数 add()我想知道在 oop 编程中它会导致什么
您在 "public" 之后缺少 "function"。
它不起作用的原因有几个:
public __construct(){};
不是定义 class 构造的正确方法。
如果这只是一个拼写错误,您将得到的实际错误是:
Fatal error: Call to a member function getDefinition() on a non-object in ...
这是因为如果你扩展一个有结构的 class,那么你必须调用父结构,否则它将被丢弃。 (which it does).
所以在这里将它们 2 点放在一起是一个有效的例子:
<?php
// require 'vendor/autoload.php';
use League\Container\Container;
class App extends Container {
public function __construct() {
parent::__construct();
}
}
class Foo {
}
$container = new App;
// add foo to the container
$container->add('foo', 'Foo');
// retrieve foo from the container
$service = $container->get('foo');
var_dump($service instanceof Foo); // true