开发者

PHP OOP properity constant usage

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 contru开发者_运维百科ctor.

Edit2:

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


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.


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;
    }
}


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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜