简体   繁体   English

OOP PHP需要类,扩展

[英]OOP PHP require classes, extends

Currently I am trying to understand how OOP applies to PHP and I am having trouble with calling my class when I am getting into inheritance. 目前,我试图了解OOP如何应用于PHP,并且在继承时无法调用类。

I am using the following PHP code: 我正在使用以下PHP代码:

require_once("init.php");

$table = new Table();
$table->draw();

$customer1 = new Customer();

Since the table class is just a plain class (not inherited) it will load correctly. 由于表类只是一个普通类(未继承),它将正确加载。

The init.php has the following PHP code: init.php具有以下PHP代码:

function __autoload($class_name) {
require_once('classes/'.$class_name . '.class.php');
}

Because the Customer class is inhereting the User class, the code for the Customer class is inside the User class, however the __autoload function is trying to call for the customer.class.php now. 因为Customer类正在插入User类,所以Customer类的代码位于User类内部,但是__autoload函数现在尝试调用customer.class.php。

My Customer class would look something like this: 我的客户类如下所示:

class User
{
    private $_username;

    public function __construct($name)
    {
        $this->_username = $name;
    }

    public function getUsername()
    {
        return $this->_username;
    }
}

class Customer extends User
{
    public function __construct()
    {
        //some code here
    }
}

Cany anyone explain me please how I should call an inherited class with PHP? 谁能解释一下我如何用PHP调用继承的类?

You should only have one class per file. 每个文件只能有一个类。 Your autoload will handle everything for you as long as every class is in its own file, named the same way... 只要每个类都在自己的文件中,自动加载将为您处理所有事情,命名方式相同...

Put all your Customer class code inside Customer.class.php 将所有客户类代码放入Customer.class.php

Each class should be written in its own file, exactly because of this autoload. 正是由于这种自动加载,每个类都应该写在自己的文件中。 There's no reason why class Customer must be within the same file as class User , just put it in its own file and your autoloader will handle it correctly. 没有理由为什么class Customer必须与class User位于同一文件中,只需将其放在自己的文件中,您的自动加载器就可以正确处理它。

Otherwise, you'll have to adopt some other naming scheme and write a more intelligent autoloader which can find classes in files with different names. 否则,您将不得不采用其他一些命名方案,并编写一个更智能的自动加载器,该加载器可以在具有不同名称的文件中查找类。 (Don't do that, not really.) (不要那样做,不是真的。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM