代码之家  ›  专栏  ›  技术社区  ›  Jalal

尝试在php中提供类参数时出错

  •  0
  • Jalal  · 技术社区  · 16 年前

    我像这样宣布课程:

    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!';}
    }
    

    在主代码中:

    $foo2 = new Foo2();
    $bar = new Bar($foo2);
    

    主代码中出现此错误的原因是什么:

    Fatal error: Default value for parameters with a class type hint can only be NULL
    

    php版本:PHP5.3.2

    --------------------------------------更新了----------------------------------------

    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;
    }
    

    }

    文件: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);
            }
    
        }
    }
    

    错误:

    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) 
    
    1 回复  |  直到 16 年前
        1
  •  2
  •   Charles    16 年前

    感谢您提供完整的代码,以下是您的错误:

    public function __construct(data\DBConnection $connection, int $type = 0)
    

    PHP5.3只支持数组和类的类型暗示。

    int $type = 0 班 命名为“int”,并对其进行解析,即使该类不存在。

    considering adding other type hints in the future . 有 currently code in PHP's trunk


    编辑:在挖掘了PHP的内部结构之后,我发现 the latest Type Hinting 线程。看起来像 this the current Type Hinting RFC ,但在方向上似乎没有达成共识。Zeev想回滚提交,但不清楚是否完成了。

    推荐文章