【问题标题】:Fatal error: Cannot call constructor in C:\wamp\www\starter\***.php on line 8致命错误:无法在第 8 行的 C:\wamp\www\starter\***.php 中调用构造函数
【发布时间】:2014-08-03 10:39:29
【问题描述】:

您好,我正在尝试学习 PHP OOP,但我遇到了这个错误,我不明白为什么?

无法在 Skipper 中调用构造函数->__construct()

<?

    $user1 = new Skipper('Steven', 'Smith', 'steve@website.com.au', 'Yes');
    echo '<p>First Name: ' . $user1->getFirstName() .'</p>';
    echo '<p>Last Name: ' . $user1->getLastName() .'</p>';
    echo '<p>Email: ' . $user1->getEmail() .'</p>';
    echo '<p>Skipper: ' . $user1->getSkipper() .'</p>';
?>


<?php

    class User
    {
    protected $_first_name;
    protected $_last_name;
    protected $_email;

       public function getFirstName()
       {
        return $this->_first_name;
        }

        public function getLastName()
       {
        return $this->_last_name;
        }

        public function getEmail()
       {
        return $this->_email;
        }       
    };

?>


<?php

    class Skipper extends User
    {
    protected $_skipper;

        public function __construct($first_name, $last_name, $email, $skipper) 
       {
        parent::__construct($first_name, $last_name, $email);
        $this->_skipper = $Skipper;
        }

        final public function getSkipper()
        {
        return $this->_skipper;
        }
    }

?>  

【问题讨论】:

  • 你应该重新格式化代码并给我们 Skipper 类的完整代码
  • 请格式化你的代码,没有你的类的源代码就无法理解发生了什么。
  • 如果父构造函数不存在就不要调用它。 PHP 类没有默认构造函数。当且仅当定义了一个构造函数时,一个类才具有一个构造函数。更多代码会有所帮助。
  • Skipper 类构造函数中,您正在调用父构造函数,即User 类构造函数,它不存在..
  • @Syed Qarib 没错,就像我已经说过的那样。

标签: php oop constructor


【解决方案1】:

在父类User中创建构造函数或者不要调用Skipper类中的构造函数。

在您的情况下,我认为您想要将此构造函数添加到您的 User 类中:

public function __construct($first_name, $last_name, $email) 
{
    $this->_first_name = $first_name;
    $this->_last_name = $last_name;
    $this->_email = $email;
}

在这个小“修复”之后,错误应该不会再出现了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-19
    • 2015-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多