Error while trying feed a class parameter in php
i declared classes like this:
class Foo{ public function __construct(){ echo 'Foo was created!';} }
class Foo2 extends Foo{ public function __construct(){ parent::__construct(); echo 'Foo2 was created!';} }
class Bar{
public function __construct(Foo $foo){ echo 'Bar was created!';}
}
in main code:
$foo2 = new Foo2();
$bar = new Bar($foo2);
What is reason of this error in main code:
Fatal error: Default value for parameters with a class type hint can only be NULL
php version: PHP 5.3.2
---------------------开发者_运维问答-----------------Updated!----------------------------------------
file: system.data.php
namespace system\data{
include ('system.php');
use system;
class DBConnection implements system\IDisposable {
protected $serverName;
protected $userId;
protected $password;
protected $handler;
protected $isOpened;
/*
* create a new instance of DBConnection.
*/
public function __construct($server, $uid, $password) {
$this->isOpened = false;
$this->serverName = $server;
$this->userId = $uid;
$this->password = $password;
}
class DBCommand implements \system\IDisposable {
public function __construct(DBConnection $connection, int $type) {
$this->connection = $connection;
$this->queryType= $type;
}
}
file: system.data.mysql.php
namespace system\data\mysql{
class MySqlCommand extends DBCommand {
public function __construct(data\DBConnection $connection, int $type = 0) {
parent::__construct($connection, $type);
}
}
class MySqlConnection extends DBConnection {
public function __construct($server, $uid, $password) {
parent::__construct($server, $uid, $password);
}
}
}
error:
Fatal error: Default value for parameters with a class type hint can only be NULL in C:\Program Files\Apache Software Foundation\...\system.data.mysql.php on line 35(constructor declartion)
Thank you for the full code, here's your error:
public function __construct(data\DBConnection $connection, int $type = 0)
PHP 5.3 only supports type hinting for arrays and classes.
Your declaration of int $type = 0
is looking for a class named "int", and parses it as such, even if the class doesn't exist.
You'll need to remove the bogus type hint. The PHP developers are considering adding other type hints in the future. There's currently code in PHP's trunk to perform type hinting for scalar values, but much has changed since that blog article was posted. I'll see if I can track down the current state of things, but searching the PHP internals mailing list is a dreadfully horrible task.
Edit: After digging through PHP Internals, I found the latest Type Hinting thread. It looks like this the current Type Hinting RFC, but there doesn't appear to be consensus on the direction. Zeev wanted to rollback the commit, but it's not clear if that was done.
精彩评论