haunted85
haunted85

Reputation: 1671

How to make sure an object exists before performing operations

I have an index.php that loads bites of the page from other php files. At the top of the index.php I have all the require_once statements including the PHP class that handles the db connection and I also instantiate an object of that class:

<?php 
    require_once 'libs/DatabaseHandler.php';

    $dbh = new DatabaseHandler('localhost', 'root', '*******', 'pride2012');

    require_once 'pages/01_includes.php';
    require_once 'pages/02_menu.php';
    require_once 'pages/03_slider.php';
    require_once 'pages/04_news.php';   
?> 

The page-bit using the db managing class is 04_news.php, is it enough constructing the object before 04_news.php loads to make myself sure that the object exists before the database related operations start?

Upvotes: 2

Views: 2671

Answers (3)

wonzbak
wonzbak

Reputation: 8124

If you're sure that 04_news.php is never been called alone, aka not by index.php, it's enough.

You can also implement DatabaseHandler as a singleton http://en.wikipedia.org/wiki/Singleton_pattern.

Upvotes: 0

jeffjenx
jeffjenx

Reputation: 17487

Defining the object prior to the operations is enough.

Alternatively, you can use the built-in __autoload( ) method to dynamically load classes as needed.

Take a look at PHP.net: Autoloading Classes for more information.

Upvotes: 2

Brice Favre
Brice Favre

Reputation: 1527

You can try if the object exuits if it's an object and if it's an instance of DatabaseHandler.

http://php.net/manual/en/function.is-object.php

http://php.net/manual/en/internals2.opcodes.instanceof.php

Upvotes: 2

Related Questions