SitePoint Sponsor

User Tag List

Page 1 of 2 12 LastLast
Results 1 to 25 of 38
  1. #1
    SitePoint Member
    Join Date
    Aug 2013
    Posts
    5
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question PHP Procedural vs Object Oriented.

    Was just reading through a book, "PHP 5 Advanced" by Lary Ullman. He goes over OOP style PHP. I see it used often in CMS's such as WordPress, but I don't really know what the benefit is to OOP coding over Procedural coding. Can anyone help explain the pro's and con's of each and share your personal opinions on each?

  2. #2
    SitePoint Addict bronze trophy
    Join Date
    Apr 2013
    Location
    Ithaca
    Posts
    351
    Mentioned
    6 Post(s)
    Tagged
    1 Thread(s)
    Procedural programming is for amateurs, OOP on the other hand is what it takes for professional programming. In a perfect script, everything is an object.

    OOP offers encapsulation, inheritance, polymorphism and composition, it helps you build much more extendable, reusable, maintainable, and organized application. The advantages are more evident in larger programs, which are pretty much impossible to work on with procedural style, especially when teamwork is required.

    For newbies, I'd recommend you to work on a project and learn step by step on why OOP will help you create better software. As your application grows in size and complexity, you will realize how it's difficult or impossible to extend your application further if its written in procedural style. At this point, you won't ever want to code in procedural php any longer.

  3. #3
    Community Advisor bronze trophy
    fretburner's Avatar
    Join Date
    Apr 2013
    Location
    Brazil
    Posts
    1,389
    Mentioned
    45 Post(s)
    Tagged
    12 Thread(s)
    Broadly speaking, the difference is that in procedural programming you create functions (procedures) which act on data structures. With OOP, you're creating objects which encapsulate both data and the methods which act on it.

    The idea behind OOP was to make programs easier to write and maintain by allowing problems to be modeled in terms of objects which represent the entities or concepts that the application deals with. One of the classic examples is that of a banking application, where you might have objects that represent customers, accounts, balance transfers, and loans etc.

    In my opinion, procedural programming is still useful for writing small, simple scripts.. you might use it when writing a utility script to periodically clean up old log files or something like that. Using objects in a scenario like this would be overkill.

    As soon as you start getting more complex with your requirements, and there's the possibility that the program might have to accomodate changes over time, then OOP is the way to go. That said, be aware that just grouping together your functions into classes doesn't make your code OO.. good OO design is something that needs to be learned and practiced.

  4. #4
    SitePoint Member
    Join Date
    Aug 2013
    Posts
    5
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks for the info guys. Maybe v2 of the CMS I'm coding will convert to OOP. Not sure though as seems like procedural is more commonly used still and the CMS will be open source for users to develop their own plugins/modifications.

    I just started the chapters on OOP, but it kinda seems like an object is similar to a function, which contains other functions.

  5. #5
    SitePoint Wizard bronze trophy Jeff Mott's Avatar
    Join Date
    Jul 2009
    Posts
    1,246
    Mentioned
    16 Post(s)
    Tagged
    0 Thread(s)
    Well, first off, let's be clear that OOP is a technique for programming. Anything you can do in OOP, you can also do in procedural. When we say a language is object oriented, that means it provides mechanisms that makes it convenient to use the object oriented style. For example, we could write object oriented programs in C, but it would be unnecessarily hard because that language doesn't support object oriented techniques.

    Now to more directly answer your question: In procedural, the focus is on the processing -- the algorithm needed to perform the desired computation. Whereas in OOP, the focus is on data organization and abstraction. It tries to make us think of our program as interacting concepts rather than as a bunch of data with functions twiddling their bits. The goal is to write programs that scale better and are more adaptable to change.
    "First make it work. Then make it better."

  6. #6
    Just Blow It bronze trophy
    DaveMaxwell's Avatar
    Join Date
    Nov 1999
    Location
    Mechanicsburg, PA
    Posts
    7,254
    Mentioned
    113 Post(s)
    Tagged
    1 Thread(s)
    Quote Originally Posted by Hall of Famer View Post
    Procedural programming is for amateurs, OOP on the other hand is what it takes for professional programming. In a perfect script, everything is an object.

    OOP offers encapsulation, inheritance, polymorphism and composition, it helps you build much more extendable, reusable, maintainable, and organized application. The advantages are more evident in larger programs, which are pretty much impossible to work on with procedural style, especially when teamwork is required.
    Wow....I'd certainly disagree to statement #1, and with the end of statement #2.

    This is from a lecture on java, it's a pretty good explanation on OOP and the differences with procedural programming. http://www.ctp.bilkent.edu.tr/~russe...OOConcepts.htm

    I've written in both, and have seen true cludge and spaghetti code from both. The benefit I've personally seen from procedural is it tends to force people to think a little before writing. What I've seen in OOP far too many times is people trying to throw an override method which calls another override, which calls another override, etc. when it would make more sense to take a moment to re-engineer the methods.

    The biggest difference to me is the approach - procedural focuses more on functionality (ideally each procedure focuses on one piece of functionality), and OOP is focused on considering everything as an object.

    Edit:

    Jeff spelled it out better than me
    Dave Maxwell - Manage Your Site Team Leader
    My favorite YouTube Video! | Star Wars, Dr Suess Style

  7. #7
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,892
    Mentioned
    211 Post(s)
    Tagged
    12 Thread(s)
    Hi,

    Quote Originally Posted by c.nickerson View Post
    He goes over OOP style PHP. I see it used often in CMS's such as WordPress
    I know this doesn't really contribute much to the discussion at hand, but isn't WordPress's code base largely procedural?
    Or are you talking about various WP plugins?

  8. #8
    Non-Member
    Join Date
    Oct 2007
    Posts
    363
    Mentioned
    11 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by DaveMaxwell View Post
    Wow....I'd certainly disagree to statement #1, and with the end of statement #2.

    This is from a lecture on java, it's a pretty good explanation on OOP and the differences with procedural programming. http://www.ctp.bilkent.edu.tr/~russe...OOConcepts.htm

    I've written in both, and have seen true cludge and spaghetti code from both. The benefit I've personally seen from procedural is it tends to force people to think a little before writing. What I've seen in OOP far too many times is people trying to throw an override method which calls another override, which calls another override, etc. when it would make more sense to take a moment to re-engineer the methods.

    The biggest difference to me is the approach - procedural focuses more on functionality (ideally each procedure focuses on one piece of functionality), and OOP is focused on considering everything as an object.

    Edit:

    Jeff spelled it out better than me

    I find the direct opposite to be true. In my experience, procedural programming tends to have almost no thought behind it - just make the functionality and be done with it. This leads to systems that are generally very messy and hard to extend in the future.

    On the other hand, OOP (done well) is all about thinking about how your application may need to adapt over time - good OO systems have very focused objects that do one thing well - a good system will have nice clean interfaces that makes expansions and adjustments really easy. If I'm writing a reporting system for example, I'll tend to focus on the interfaces for my report objects first - I'd then make a bunch of writer objects that take the report interface and output the report in whatever format I want. This would mean I could create new reports easily, and combined with separate report writers, I could output to excel, json, csv etc etc, and every element would stay compatible with every other element.

    OOP done well leads to nice clear designs that are easy to work with an expand upon. Unfortunately, there is a lot of php code out there that uses classes, but is not actually object oriented, and it seems from what you've said, that this is the kind of code you have experienced in the past.

  9. #9
    SitePoint Member
    Join Date
    Aug 2013
    Posts
    5
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Pullo View Post
    Hi,



    I know this doesn't really contribute much to the discussion at hand, but isn't WordPress's code base largely procedural?
    Or are you talking about various WP plugins?
    I'm not sure about all their code but I know to access a lot of variables they use OOP style variables. WP is just sloppy in my personal opinion.

    I use SmartyPHP template system for my CMS and it uses OOP. $smarty->assign('variable_name', 'variable value');

  10. #10
    Always A Novice bronze trophy
    K. Wolfe's Avatar
    Join Date
    Nov 2003
    Location
    Columbus, OH
    Posts
    2,178
    Mentioned
    63 Post(s)
    Tagged
    2 Thread(s)
    Quick n dirty list of benefits of object oriented design. The main bullet point of OOP is less code (if done right). From there we can get these much more important points:


    1. Readability - You may not think so since your new to it, but I kill over being handed a large procedural project management wants modified.
    2. Ease of changes - Make changes in once place rather than many
    3. Stability - Less chance for slightly different code being produced in multiple places. This is a HUGE deal with bigger projects. HUGE. Did I mention HUGE? A bigger PHP project without strict OO concepts is the first step toward failure.


    Beginner Example:

    Imagine writing an application that has to make a database connection multiple times (across multiple scripts). Each time you write it out you have at least 2-3 lines dedicated just to the connection. If you ever change credentials or location of the database, you'd have to come back to each page and make the change. A proper OOP setup would mean you only initiate a new DB object that you created which handles your connection for you. Now you or another developer only needs to make a change in one location rather than 10.

  11. #11
    SitePoint Guru bronze trophy
    Join Date
    Dec 2003
    Location
    Poland
    Posts
    930
    Mentioned
    7 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by K. Wolfe View Post
    Beginner Example:

    Imagine writing an application that has to make a database connection multiple times (across multiple scripts). Each time you write it out you have at least 2-3 lines dedicated just to the connection. If you ever change credentials or location of the database, you'd have to come back to each page and make the change. A proper OOP setup would mean you only initiate a new DB object that you created which handles your connection for you. Now you or another developer only needs to make a change in one location rather than 10.
    While this is a good example showing how to structure things right I don't see it as having anything to do with procedural vs object-oriented. In procedural you simply create the db connection once and store it in a global variable to be accessed by all functions and when credentials change they are still in one place. Or, you create a single function for fetching the db connection and use it everywhere. Or, you store the credentials in a single config file, which can be done with procedural code as well. So I think a better "Begginer Example" would be better .

    But yes, I've seen procedural code where the same db credentials were scattered around 10 different files - this was a pretty large online shop that I inherited to work on and the end result was that I decided to write it again from scratch .

  12. #12
    SitePoint Evangelist
    Join Date
    May 2006
    Posts
    426
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Pullo View Post
    isn't WordPress's code base largely procedural?
    Correct. In fact, that is a good relevant point. WP's core code is a bit of a mess. While using objects doesn't guarantee your code is neat and well organised, it certainly does help. What I love with objects is how relevant functions are grouped together and relationship between different functions is better described. Having written procedural for years, I relatively recently moved to objects and it's like new life has been breathed into my code.

    I use procedural functions for any site-spefiic niche functions but everything else is done with class/objects.

  13. #13
    Non-Member
    Join Date
    Oct 2007
    Posts
    363
    Mentioned
    11 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Lemon Juice View Post
    While this is a good example showing how to structure things right I don't see it as having anything to do with procedural vs object-oriented. In procedural you simply create the db connection once and store it in a global variable to be accessed by all functions and when credentials change they are still in one place. Or, you create a single function for fetching the db connection and use it everywhere. Or, you store the credentials in a single config file, which can be done with procedural code as well. So I think a better "Begginer Example" would be better .

    But yes, I've seen procedural code where the same db credentials were scattered around 10 different files - this was a pretty large online shop that I inherited to work on and the end result was that I decided to write it again from scratch .
    Creating a global variable would be absolutely horrible. Globals are evil.

  14. #14
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,892
    Mentioned
    211 Post(s)
    Tagged
    12 Thread(s)
    Quote Originally Posted by aaarrrggh View Post
    Creating a global variable would be absolutely horrible. Globals are evil.
    I'm following along from the sidelines here and just wondered, given that globals are evil, what would be your preferred method of making a database connection multiple times (across multiple scripts) using procedural code?

  15. #15
    SitePoint Guru bronze trophy
    Join Date
    Dec 2003
    Location
    Poland
    Posts
    930
    Mentioned
    7 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by aaarrrggh View Post
    Creating a global variable would be absolutely horrible. Globals are evil.
    This is not the point. I just pointed out how they could be used to keep database credentials in a centralized place using procedural programming.

    Quote Originally Posted by Pullo View Post
    I'm following along from the sidelines here and just wondered, given that globals are evil, what would be your preferred method of making a database connection multiple times (across multiple scripts) using procedural code?
    Back in the days when I used procedural programming only I used a global variable and it worked well. But I produced a lot of spaghetti code so I'm not sure if this was the best way.

    Maybe a singleton-ish function like getDbConnection() would be better. I don't know if passing around a database handle would be feasible in procedural.

    But anyway, this database connection problem didn't really exist back in the old PHP days because the old mysql functions didn't require the connection handle so I could simply connect at the beginning of the script and call mysql_query() in any scope without worrying about passing the connection if I used only one database. That was pure genius in its simplicity!

  16. #16
    Non-Member
    Join Date
    Oct 2007
    Posts
    363
    Mentioned
    11 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Pullo View Post
    I'm following along from the sidelines here and just wondered, given that globals are evil, what would be your preferred method of making a database connection multiple times (across multiple scripts) using procedural code?
    Well I don't write procedural code, and haven't for a long time... probably about 3-4 years by now.

    My code nowadays uses namespaces in php, and all my autoloading is done based on namespaces too, so I don't need require/include statements all over the place either...

    I guess to do this in a procedural way, I'd probably have some kind of dbConnect() function, that would take a constant as a parameter... The constant would point to some config file (like a yaml or xml file) that would contain the database connection details. The script would then create the database connection based on those details.

    So for example, if I wanted to connect to two different databases, I could do $connectionA = dbConnect(DATABASE_A);, and for the other I could do $connectionB = dbConnect(DATABASE_B);

    If I needed to change the password settings or whatever, I'd change it in the mapping file. There'd be a direct connection between a parameter in the mapping file and the constant value (so it'd be like: DATABASE_B = 'report_database' and then in the yaml file or whatever, there'd be a 'report_database' key).

    Does that make sense?

    I'd probably do something like that...

  17. #17
    SitePoint Member
    Join Date
    Feb 2009
    Posts
    17
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Pullo View Post
    I'm following along from the sidelines here and just wondered, given that globals are evil, what would be your preferred method of making a database connection multiple times (across multiple scripts) using procedural code?

    The only thing you are really left with to mind is to wrap it in a function that maintains the static state internally.

    PHP Code:
    /**
    * @return Db
    */
    function getDb(){
        static 
    $db;
        if( isset(
    $db) ){
            return 
    $db;
        }

        
    $db = new Db();
        return 
    $db;

    Two of the only real benefits I can think of are

    1 . That is the state is sealed, a global variables very basic existance is too exposed.
    eg.

    PHP Code:
    class Db{
        function 
    getUsers(){


        }
    }


    $db = new Db();
    function 
    a(){    
        global 
    $db;
        
    $db->getUsers();
        
    $db null;
    }


    function 
    b(){
        global 
    $db;
        
    $db->getUsers(); //fatal where has the db gone in the call chain?
    }


    a();
    b(); 
    Whereas
    PHP Code:
    class Db{
        function 
    getUsers(){


        }
    }

    function 
    getDb(){
        static 
    $db;
        if( isset(
    $db) ){
            return 
    $db;
        }

        
    $db = new Db();
        return 
    $db;
    }


    function 
    a(){
        
    $db getDb();
        
    $db->getUsers();
        
    $db null;
    }


    function 
    b(){
        
    $db getDb();
        
    $db->getUsers(); //nullification of object can only happen in getDb()
    }


    a();
    b(); 

    2. If logic is required at point of request such as for debugging it can be easily added or a break point can be set.

    eg.
    PHP Code:
    function getDb(){
        
    file_put_contents'getDbLog.txt'print_r(debug_backtrace(), true ), FILE_APPEND );
        static 
    $db;
        if( isset(
    $db) ){
            return 
    $db;
        }

        
    $db = new Db();
        return 
    $db;

    .

  18. #18
    Non-Member
    Join Date
    Oct 2007
    Posts
    363
    Mentioned
    11 Post(s)
    Tagged
    0 Thread(s)
    Your first example is what I was thinking here (except getDb() would accept a parameter which could be used to determine which db connection to return) - the only thing is, I wasn't sure whether you could use a static variable outside of a class scope - it's possible to do that just in a function then is it?



    Quote Originally Posted by pbyrne84 View Post
    The only thing you are really left with to mind is to wrap it in a function that maintains the static state internally.

    PHP Code:
    /**
    * @return Db
    */
    function getDb(){
        static 
    $db;
        if( isset(
    $db) ){
            return 
    $db;
        }

        
    $db = new Db();
        return 
    $db;

    Two of the only real benefits I can think of are

    1 . That is the state is sealed, a global variables very basic existance is too exposed.
    eg.

    PHP Code:
    class Db{
        function 
    getUsers(){


        }
    }


    $db = new Db();
    function 
    a(){    
        global 
    $db;
        
    $db->getUsers();
        
    $db null;
    }


    function 
    b(){
        global 
    $db;
        
    $db->getUsers(); //fatal where has the db gone in the call chain?
    }


    a();
    b(); 
    Whereas
    PHP Code:
    class Db{
        function 
    getUsers(){


        }
    }

    function 
    getDb(){
        static 
    $db;
        if( isset(
    $db) ){
            return 
    $db;
        }

        
    $db = new Db();
        return 
    $db;
    }


    function 
    a(){
        
    $db getDb();
        
    $db->getUsers();
        
    $db null;
    }


    function 
    b(){
        
    $db getDb();
        
    $db->getUsers(); //nullification of object can only happen in getDb()
    }


    a();
    b(); 

    2. If logic is required at point of request such as for debugging it can be easily added or a break point can be set.

    eg.
    PHP Code:
    function getDb(){
        
    file_put_contents'getDbLog.txt'print_r(debug_backtrace(), true ), FILE_APPEND );
        static 
    $db;
        if( isset(
    $db) ){
            return 
    $db;
        }

        
    $db = new Db();
        return 
    $db;

    .

  19. #19
    SitePoint Wizard bronze trophy Jeff Mott's Avatar
    Join Date
    Jul 2009
    Posts
    1,246
    Mentioned
    16 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Pullo View Post
    I'm following along from the sidelines here and just wondered, given that globals are evil, what would be your preferred method of making a database connection multiple times (across multiple scripts) using procedural code?
    I imagine that would be a function -- get_db_connection or whatever -- that you could call from some local scope when you need it. If you think get_db_connection might be called multiple times, then you could use the static keyword to "cache" the db link and return the same value each time.

    Of course, the even better option would be the dependency injection / front controller style. (Remember that OOP is a technique, and we can still use that technique even if we don't use classes.)

    PHP Code:
    <?php

    function app($request)
    {
        
    // connect to database
        
    $db = new PDO('mysql:host=localhost;dbname=<SOMEDB>''<USERNAME>''PASSWORD');

        
    // route and do action
        
    if ($request == '/hello') {
            
    hello_action($db);
        }
    }

    function 
    hello_action($db)
    {
        echo 
    'Hello, World!';
    }

    app('/hello');
    "First make it work. Then make it better."

  20. #20
    SitePoint Wizard bronze trophy Jeff Mott's Avatar
    Join Date
    Jul 2009
    Posts
    1,246
    Mentioned
    16 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by pbyrne84 View Post
    function a(){
    global $db;
    $db->getUsers();
    $db = null;
    }
    That's a great example of how globals can be dangerous. Any line from anywhere in the program could clobber or otherwise alter a global variable, and there's no easy way to trace where that clobbering happened. So you end up with code that just doesn't work for some inexplicable reason.
    "First make it work. Then make it better."

  21. #21
    Non-Member
    Join Date
    Oct 2007
    Posts
    363
    Mentioned
    11 Post(s)
    Tagged
    0 Thread(s)
    So my version would be something like this (I'm just modifying pbyrne84's post) here:


    PHP Code:

    define
    ('REPORTING_DATABASE''reporting_database');
    define('MAIN_APP_DATABASE_1''main_app_db_1');

    /**
    * @return Db
    */
    function getDb($dbName){
        static 
    $db;
        if( isset(
    $db) ){
            
    //logic to parse the config file goes here
            
    return $db;
        }
        
    $db = new Db();
        return 
    $db;
    }  

    //calling the function:
    $db getDb(MAIN_APP_DATABASE_1); 
    Then I'd have a config file with something like this:

    Code:
    reporting_database:
       host: xxx.xxx.xxx.xxx
       dbname: reporting
       dbusername: geoff
       dbpassword: hello
       dbport: 561
    
    
    main_app_db_1:
       host: xxx.xxx.xxx.xxx
       dbname: main_1
       dbusername: geoff
       dbpassword: kjeifjeoj
       dbport: 561
    The constants would map to the keys in the config file. Using the static variable would mean you would only have to do the parse of the file once on each request.

  22. #22
    Always A Novice bronze trophy
    K. Wolfe's Avatar
    Join Date
    Nov 2003
    Location
    Columbus, OH
    Posts
    2,178
    Mentioned
    63 Post(s)
    Tagged
    2 Thread(s)

    Post

    But see you can avoid stuff like:

    Code PHP:
        if( isset($db) ){
            return $db;
        }

    in your DB function (which btw wont work unless you use a global $db (ugly and dangerous), you go to OO method: Heres how I like to do it.

    Code PHP:
    class DbConfig {
        protected $Host;
        protected $Port;
        protected $User;
        protected $Pass;
     
        public function __construct($ConfigFile) {
            //parse ini file and pass to protected vars
        }
     
        /*
         * ALL GETTER functions
         */
     
        public function GetHost() {
            return $this->Host;
        }
     
        /*
         * etc...
         */
    }
     
    class Db {
        protected $Db;
     
        public function __construct(DbConfig $DbConfig) {
            //connect to db, set resource to Db
        }
     
        public function __destruct() {
            $this->$Db->close();
        }
     
        public function GetDb() {
            return $this->Db;
        }
    }
     
    $DbResource = new Db(new DbConfig('/path/to/this/scripts/db/settings.ini'));

  23. #23
    Non-Member
    Join Date
    Oct 2007
    Posts
    363
    Mentioned
    11 Post(s)
    Tagged
    0 Thread(s)
    He's using a static variable here:

    PHP Code:
    if( isset($db) ){
            return 
    $db;
        } 
    So it will work, and it doesn't need globals.

    Your code would have to create the database connection each time, wouldn't it? If I called it twice, I'd be creating a new db connection each time, whereas if you take my modified version of his code, you would only be returning the db handle (without using a global variable) unless you were making a connection to a different db (which actually would mean the code in my case should be modified to store an array of handles and return if created already, if not - create the connection)...

    I just didn't realise you could use static variables in a function outside of a class - but these are not the same as globals.

    Quote Originally Posted by K. Wolfe View Post
    But see you can avoid stuff like:

    Code PHP:
        if( isset($db) ){
            return $db;
        }

    in your DB function (which btw wont work unless you use a global $db (ugly and dangerous), you go to OO method: Heres how I like to do it.

    Code PHP:
    class DbConfig {
        protected $Host;
        protected $Port;
        protected $User;
        protected $Pass;
     
        public function __construct($ConfigFile) {
            //parse ini file and pass to protected vars
        }
     
        /*
         * ALL GETTER functions
         */
     
        public function GetHost() {
            return $this->Host;
        }
     
        /*
         * etc...
         */
    }
     
    class Db {
        protected $Db;
     
        public function __construct(DbConfig $DbConfig) {
            //connect to db, set resource to Db
        }
     
        public function __destruct() {
            $this->$Db->close();
        }
     
        public function GetDb() {
            return $this->Db;
        }
    }
     
    $DbResource = new Db(new DbConfig('/path/to/this/scripts/db/settings.ini'));

  24. #24
    Always A Novice bronze trophy
    K. Wolfe's Avatar
    Join Date
    Nov 2003
    Location
    Columbus, OH
    Posts
    2,178
    Mentioned
    63 Post(s)
    Tagged
    2 Thread(s)
    Quote Originally Posted by aaarrrggh View Post
    He's using a static variable here:

    PHP Code:
    if( isset($db) ){
            return 
    $db;
        } 
    So it will work, and it doesn't need globals.

    Your code would have to create the database connection each time, wouldn't it? If I called it twice, I'd be creating a new db connection each time, whereas if you take my modified version of his code, you would only be returning the db handle (without using a global variable) unless you were making a connection to a different db (which actually would mean the code in my case should be modified to store an array of handles and return if created already, if not - create the connection)...

    I just didn't realise you could use static variables in a function outside of a class - but these are not the same as globals.
    Everytime you initiate a new object, it will create a new connection, which is the proper behavior. You can reuse the same object that was already initiated to use the same connection.

  25. #25
    Non-Member
    Join Date
    Oct 2007
    Posts
    363
    Mentioned
    11 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by K. Wolfe View Post
    Everytime you initiate a new object, it will create a new connection, which is the proper behavior. You can reuse the same object that was already initiated to use the same connection.
    But the challenge is to pass around the database connection in a procedural style without using globals. This function would do it - if you call it after the db is created, you'll just receive the handle. If the handle isn't created already, the connection will be made and the handle will be returned.

    I'm not sure I agree a new connection should be created each time anyway. It'd be more resource heavy, unless you're planning to just pass the database handle around all over the place?


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •