Re: new $foo->className(); Class name must be a valid object or a string
| From: | Stut | Date: | Sun, 04 May 2008 00:31:28 +0000 |
| Subject: | Re: new $foo->className(); Class name must be a valid object or a string | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-273848@lists.php.net to get a copy of this message | ||
On 4 May 2008, at 00:46, Jack Bates wrote:
I am trying to load PHP objects stored in a database, where the class name is stored in a column: $object = new $resultSet->getString(1); This fails for the same reason that the following fails: <?php class Foo { public function className() { return 'Foo'; } } $foo = new Foo; $bar = new $foo->className();I would rather have a factory method that returns a new instance of the class. There's no need for the outside world to know the class name. <?php class Foo {
public function newInstance()
{
return new self();
}
public function test($a)
{
echo 'test: '.$a."\n";
}
}
$foo = new Foo;
$foo->test('foo');
$bar = $foo->newInstance();
$bar->test('bar');
?>
However, if you insist on doing it your way can I make a small suggestion? It's better to spend your time on functionality rather than finding ways to save some typing. I see no reason to try to combine the two statements - saving typing and a pitiful amount of disk space are the only benefits.
-Stut
--
http://stut.net/