SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Zealot
    Join Date
    Aug 2010
    Posts
    194
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)

    can you include/require a file in a class

    is this good or bad practice:

    Code PHP:
    <?php
    require_once("Image/Barcode.php");
     
    class BarcodeClass {
     
    }

    how would you use variables/etc from the required file, in the class?

  2. #2
    Community Advisor bronze trophy
    fretburner's Avatar
    Join Date
    Apr 2013
    Location
    Brazil
    Posts
    1,408
    Mentioned
    45 Post(s)
    Tagged
    12 Thread(s)
    Hi sessions,

    Could you elaborate a little: What is in Image/Barcode.php? Data that you want to use with the BarcodeClass class?

    It don't think it's a good idea to include files from within a class unless the class is some sort of loader that is responsible for loading configuration data, autoloading classes or something along those lines. Otherwise, you probably want to be passing in any data that the class needs via the constructor or class methods.

  3. #3
    SitePoint Zealot
    Join Date
    Aug 2010
    Posts
    194
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Hi fretburner,

    thanks for looking. better sample code would have been this:

    Code PHP:
     
    <?php
    require_once("example_file.php");
     
    class ExampleClass {
     
    }

    yes, i was curious if it's possible or even good/bad practice to include a file like that, and use data from an included file from within a class.

    The class I'm building needs access to 2 different databases / 2 different instatiated database classes. I ended up passing my database connections by reference to the constructor.

    But I'm still curious if it's possible or even good/bad practice to include a file like that, and use data from an included file from within a class.

  4. #4
    SitePoint Evangelist
    Join Date
    Oct 2005
    Location
    Michigan, USA
    Posts
    434
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    I would consider that fine. If your class needs to reference a library for example, and you don't have auto loading set up, that would be the way to do it.

    You would be including that file outside of the class in your example. Including a file from within the class may produce some unexpected results.
    - Robert

  5. #5
    Non-Member
    Join Date
    Oct 2007
    Posts
    363
    Mentioned
    11 Post(s)
    Tagged
    0 Thread(s)
    It's a very bad idea, because you should be using auto loading and namespaces instead, so you shouldn't even need require or include statements.

    http://www.sitepoint.com/how-to-use-...d-autoloading/


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
  •