piekarnik Posted May 10, 2011 Share Posted May 10, 2011 Hi all, I work on a php project. I wrote it in procedural way. As project grows, it stating be harder to maintain obviously and I want to convert project ( or at lease key features) to oo code. My intention is to replace part which for example connects to database and then use the rest of the script and then move to another part write it in oo and replace old part. I wrote a simple class called Connection, just to handle connection. When I make object it connects, I retrieve some info from database using query as class function. However, there is no way I can execute my procedural login script after I made a connection object. And question is why? Do I need to write whole Database class to handle it? Can I merge oo and procedural php code together in once script? Code sample: class Connection{ // database access paramiters var $host = 'localhost'; var $data_base = 'database'; var $user = 'user'; var $pass = 'pass'; var $con_handle; // constructing object with automatic connetction to db function __construct(){ $this->connect(); } function connect(){ // open a connection to the database server $this->con_handle = new mysqli ($this->host, $this->user, $this->pass); if (mysqli_connect_errno()) { echo("Could not open connection to database server"); exit; } // selecting database $this->con_handle->select_db($this->data_base) or die(mysql_error()); } } //{ few includes here} $connection= new Connection(); //{rest of my login script} Quote Link to comment https://forums.phpfreaks.com/topic/235994-transformation-from-procedural-to-oo-code/ Share on other sites More sharing options...
trq Posted May 10, 2011 Share Posted May 10, 2011 Firstly, you cannot convert procedural code to OOP, the design principles are entirely different. You will just end up with procedural code wrapped in OO syntax. Now, your issue: A __construct returns an instance of an object, in this case your Connection object. Your Connection object in turn doesn't have any means to expose an actual connection. You would actually need to return $this->con_handle from your connect() method then use it something like.... $connection= new Connection(); $actualconnection = $connection->connect(); Quote Link to comment https://forums.phpfreaks.com/topic/235994-transformation-from-procedural-to-oo-code/#findComment-1213314 Share on other sites More sharing options...
piekarnik Posted May 19, 2011 Author Share Posted May 19, 2011 Thx thorpe. Quote Link to comment https://forums.phpfreaks.com/topic/235994-transformation-from-procedural-to-oo-code/#findComment-1217440 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.