tags:

views:

115

answers:

3

Hi there.

I'm really new to OOP. I'm even not a newbie - I'm noob. So. I want to transfer my pseudo-CMS from "normal" programming, into OOP programming system. And so:

private static $dsn = DB_TYPE.':host='.DB_HOST.';dbname='.DB_NAME;

What here causes problem? Usage of constraints? I don't know. My editor (aptana studio) shows error after 1 constant. Thanks

Edit:

Thanks for fast reaction. I'll do it in contructor.

Edit2:

But what if i want to use singleton? How to pass arguments to contructor?

+1  A: 

The problem is that properties have to be inline constants when you put them in the initializer fields.

What you're doing won't work, but this, for example, would:

private static $dsn = 'mysql:host=localhost;dbname=mydb';

I know, it's stupid, but you can't even use PHP constants. You have to literally have it in plain text.

The solution to this is to initialize $dsn in the class's constructor, like this:

class MyClass
{
    public function __construct()
    {
        self:: $dsn = DB_TYPE.':host='.DB_HOST.';dbname='.DB_NAME;
    }
}
ryeguy
+1 for the example
Josh
+3  A: 

All variable declarations must be completely static. This means not use of constants, variables, or other changeable items.

To make anything that is not completely plain text, you should use the constructor.

Chacha102
+1 just note that it might not make sense to set static members in the,constructor,because then you then cannot assume that static methods etc. will behave properly before the class has been instantiated somewhere. but php doesn't have static initializers or anything so it's hard
Tom Haigh
+1  A: 

See the documentation:

This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

You cannot concatenate strings when defining class properties.

Example from the documentation (for completness):

<?php
class SimpleClass
{
   // invalid property declarations:
   public $var1 = 'hello ' . 'world';
   public $var2 = <<<EOD
hello world
EOD;
   public $var3 = 1+2;
   public $var4 = self::myStaticMethod();
   public $var5 = $myVar;

   // valid property declarations:
   public $var6 = myConstant;
   public $var7 = array(true, false);

   // This is allowed only in PHP 5.3.0 and later.
   public $var8 = <<<'EOD'
hello world
EOD;
}

?>

As you switch to OOP anyway you should not use constants. Pass those values to the constructor of your class:

public function __construct($db_type, $db_host, $db_name) {
    self::$dsn = $db_type.':host='.$db_host.';dbname='.$db_name;
}
Felix Kling