Re: Static vs. Instantiated Objects in PHP
| From: | Jochem Maas | Date: | Fri, 21 Apr 2006 05:53:45 +0000 |
| Subject: | Re: Static vs. Instantiated Objects in PHP | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-234461@lists.php.net to get a copy of this message | ||
statically calling a method is faster than init'ing an object
then calling a method.
static methods (as opposed to functions in the global space) automatically
give a sort of namespacing, and a way to organise code (although that rather
cosmetic).
methods that are defined as static do not define $this in their
function scope, ever.
additionally classes in php5 can have static (therefore with class scope)
variables - which make static methods that much ore interesting as a
problem solving mechanism (imho) e.g.
<?php
class Test
{
static private $instance;
static function getInst()
{
if (!isset(self::$instance)) {
self::$instance = new self;
}
return self::$instance;
}
}
?>
oh look I just implemented a singleton pattern. a rather simple
example but maybe it gives you some ideas.
Mark Baldwin wrote:
Greetings all, Does anyone know how static objects work behind the scenes in PHP5? More specifically, is there a benefit to declaring an object and its methods as static vs the more traditional OO way of instantiating an object and then calling methods through the -> operator? For example if I have: class Example {public static function doSomething() { /* doing something here */ }} and class Example {private __construct() { /* constructing here */ } public function doSomething() { /* doing something here */ }} Is it more/less/equally efficient for the engine and parser to do: $result = Example::doSomething(); or $example = new Example(); $result = $example->doSomething(); Thanks in advance, Mark