Re: How can I do this -- method chaining

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Nathan Nobbe wrote:
On Jan 29, 2008 7:27 PM, Stut <stuttle@xxxxxxxxx> wrote:
Personally I'd use a static method in this instance.

thats what i recommended.

If you need to create
an instance of the class you can do so in the static method and that way it
will get destroyed when the function is done. Otherwise the object scope is
far larger than it needs to be, which IMHO is an unnecessary waste of
resources and certainly less aesthetic.

lost you on this part ..
whether you create an instance in client code by calling new or
encapsulate the call
to new in a simple factory method there will still be only one
instance of the class,
and it will still be in scope once the method is finished executing,
because all it does
is return an instance of the class its a member of.
maybe you mean something other than what i posted earlier when you say
static method?

You posted a singleton pattern. That means that from the moment you call the static method until the end of the script that object exists. That's probably fine for web-based scripts that don't run for long, but I live in a world where classes often get used in unexpected ways so I tend to write code that's efficient without relying on the environment it's running in to clean it up.

This was your code...

<?php
class Test {
    public static function getInstance() {
        return new Test();
    }

    public function doSomething() {
        echo __METHOD__ . PHP_EOL;
    }
}
Test::getInstance()->doSomething();
?>

This would be my implementation...

<?php
class Test {
    public static function doSomething() {
        $o = new Test();
        $o->_doSomething();
    }

    protected function _doSomething() {
        // I'm assuming this method is fairly complex, and involves
        // more than just this method, otherwise there is no point
        // in creating an instance of the class, just use a static
        // method.
    }
}
Test::doSomething();
?>

Of course this is just based on what the OP said they wanted to do. If there is no reason to create an instance of the object then don't do it. It's fairly likely that I'd actually just use a static method here, but it depends on what it's actually doing.

But as I said earlier, each to their own.

-Stut

--
http://stut.net/

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux