PHP: How to create object from within a class' static function

Discussion in 'Web Design and Development' started by ppc_michael, Oct 20, 2009.

  1. ppc_michael Guest


    Apr 26, 2005
    Los Angeles, CA
    If I'm in a Class' static function, can I create a new object of that same Class using some sort of $this-> or self:: notation, instead of using the actual class name? So that I can rename the class without having to go through my static functions and changing the class name in there too?

    Like, let's say I'm in a static function called Comment::getCommentCount(). If I want to access another static function, I can use
    instead of
    . I'd like to be able to create a new object a similar way, like, for example
    $obj = new self();
    instead of
    $obj = new Comment();
    (in PHP)


    Edit: Wait a minute, did I just answer my own question? Using new self(); is working now. Is that the proper way of doing it?
  2. BertyBoy macrumors 6502

    Feb 1, 2009
    Yes, you nailed it. But I'm not sure that you need the () on the new self(). I don't use them.

    Just one caveat, if you use inheritance. It'll create a new class object of whatever class it is defined in. A new feature in PHP 5.3 called Late Static Bindings may be your get out of jail card if it becomes an issue. I've been waiting ages for this, but now it's here I'm not ready for the PHP 5.3 upgrade and all the cpde re-writes to take advantage of this.

Share This Page