Jump to content

How to access method of another class


sunilvadranapu

Recommended Posts

Hi,

  I have developed one PHP class- DBConnection to connect Database and another class-Logger for logging the information like connection success or failure and event information. Now how can i access WriteLog method of Logger class in connect() method of DBConnection Class. Can you give me sample code for this.

 

Thanks in advance

 

--Sunil

 

Link to comment
https://forums.phpfreaks.com/topic/96652-how-to-access-method-of-another-class/
Share on other sites

or

<?php
class ErrorLogger
{
    function writeError($error)
    {
        // log the error
        echo '<pre>', $error, '</pre>';
    }
}

class DBConnector 
{
    private $logger;
    private $cnx;
    
    function __construct ()
    {
        $this->logger = new ErrorLogger();
    }
    
    function connect($host, $user, $pwd, $dbname)
    {
        $this->cnx = @mysql_connect ($host, $user, $pwd);
        if (!$this->cnx) 
        {
            $this->logger->writeError(mysql_error());
            return false; 
        }  
        if (!mysql_select_db ($dbname))
        {
            $this->logger->writeError(mysql_error());
            return false;
        }
    }
}

$dbc = new DBConnector;
if (!$dbc->connect('localhost','xxx','yyy','tst') )
{
    exit('Database error');
}
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.