PHP constructors and static functions

bar1024 picture bar1024 · Nov 22, 2011 · Viewed 37k times · Source

I'm a bit confused on how constructors work in PHP.

I have a class with a constructor which gets called when I instantiate a new object.

$foo = new Foo($args);

__construct($params) is called in the class Foo and it executes the appropriate initialization code.

However when I use the class to call a static function, the constructor is called again.

$bar = Foo::some_function(); //runs the constructor from Foo

This causes the constructor to execute, running the object initialization code that I intended only for when I create a new Foo object.

Am I missing the point of how constructors work? Or is there a way to prevent __construct() from executing when I use the class to make static function calls?

Should I use a "factory" function instead to do the object initialization? If so, what's the point of the constructor then?

::EDIT:: I have a form where users can upload photos to an album (create_photo.php) and an area where they can view the album (view_photos.php). Upon form submit:

$photo = new Photo($_FILES['photo'], $_POST['arg1'], ect..);

The Photo constructor creates and saves the photo. However in view_photo.php, when I call:

$photo = Photo::find_by_id($_POST['id']) //user-defined function to query database

This is causing Photo's constructor to run!

Answer

Naftali aka Neal picture Naftali aka Neal · Nov 22, 2011

I see nothing that replicates your question.

See Demo: http://codepad.org/h2TMPYUV

Code:

class Foo {
    function __construct(){ 
        echo 'hi!';
    }
    static function bar(){
        return 'there';
    }
}

echo Foo::bar(); //output: "there"