...

View Full Version : Is it possible to create an object but not call the method __construct?



Apothem
05-09-2009, 06:25 AM
Is it possible to just call an object but not run its __construct method? In other words:

class my_class {
function __construct() {
echo 'It has been constructed';
// Content here
}
//* Other methods
}
$v = new my_class;

Is it possible to just make it so that it won't run the data within the body of the method (or function?) __construct but still have all of its methods?

abduraooft
05-09-2009, 09:17 AM
You may use some conditions to skip the contents of your function, like


class my_class {
function __construct($value=true) {
if($value==false) return;
echo 'It has been constructed';
// Content here
}
//* Other methods
}
$v = new my_class(false);
btw, let me ask, what's your ultimate aim by doing this?

Apothem
05-09-2009, 06:03 PM
It's nothing too big - sometimes I want to call an object and run whatever's in its __construct method... while on other times I would want to just call an object but not run it. In my __construct method it just calls and gets a cache from a table of mine. For the "other times" I want to call my object and rebuild the cache.

Fou-Lu
05-09-2009, 10:26 PM
You know you don't require a __construct at all right? It does cause a problem with reflection, but if you're using new, a constructor is what it will try to find, but will still create the object (I don't really agree with this handling, but that's how zend chose to do it).

Sadly, with how you've described this you will always need to use some kind of conditional control. If it were something like only performing it on the first call and never again, you can control that a little easier with a static value:


class MyClass
{
private static $instances = 0;
public function __construct()
{
if (self::$instances++ <= 0)
{
// Initial load stuffs, we never need to worry about with each object again.
}
}
public function __destruct()
{
--self::$instances;
}
}


Note that this is not like the singleton pattern - __construct cannot be allowed at all in a singleton instance since you cannot reassign the value of $this.

Is that something like what you're asking to do?


Oh yes, and another idea too.
Leave the construct for an object, but move what you want to do to another method. That lets you control the call on the caller's side instead of the class' side. This is probably my recommendation, but without knowing the control scheme I can't really suggest anything else.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum