简体   繁体   English

PHP如何从另一个类访问一个类?

[英]PHP How to access a class from another class?

I have the following code: 我有以下代码:

class db { 
    //database class, connects and closes a database connection
    //some properties and methods are hided (such as host-adres, username...)

    public function connect()
    {
        mysql_connect(//parameters)or die(mysql_error());
    }
}

class ban {
    //ban class, bans an ip, again some methods and properties are hided

    public function banIP()
    {
        //here i want to access the connect function of the class db, 
        //without creating a object.
        //some code
    }
}

Now my question, from inside the method banIP() i need to connect to the database, using the function connect() from class db. 现在我的问题是,在方法banIP()我需要使用类db中的函数connect()连接到数据库。 But how do I access the connect function? 但是如何访问连接功能?

Declare an object of class db and then access it using that object, 声明一个db类的对象,然后使用该对象访问它,

   $object = new db();
   $object->connect();

You cannot access a method without creating any object. 您必须创建任何对象才能访问方法。 You will either have to create an object of the class containing the method (class db) or of the class (class ban) inheriting the class db. 您将必须创建包含方法的类的对象(类db)或继承该类db的类的对象(类ban)。

 class ban extends db {
    public function banIP()
   {
     $this->connect(); //this acts as an object.
   }
 }

Extend the class you would like to inherit those methods from. 扩展您要从中继承这些方法的类。 So, class ban should extend db. 因此,类禁令应扩展db。

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

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