简体   繁体   中英

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. But how do I access the connect function?

Declare an object of class db and then access it using that object,

   $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.

 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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