|
Posted by Manny on 06/26/07 06:21
On Jun 25, 5:15 pm, ZeldorBlat <zeldorb...@gmail.com> wrote:
> On Jun 25, 7:39 pm, Manny <thebar...@gmail.com> wrote:
>
>
>
>
>
> > Hello fellow programmers,
>
> > Recently I've run into an interesting bug? or possibly my own
> > ignorance. I wrote a class (php 4) and in the constructor made an
> > array global. Now the array is included into the file as a
> > configuration mechanism. However, the constructor for what ever reason
> > does not recognize the imported variable. Here's a summarized version
> > of the source:
>
> > config.inc:
>
> > $db['user'] = "foo";
> > $db['pass'] = "bar";
>
> > class.db.php:
>
> > require_once('config.inc');
>
> > Class db
> > {
> > var $user
> > var $pass
>
> > function db()
> > {
> > global $db;
>
> > }
>
> > }
>
> > After that point initialization occurs but $db never gets read into
> > the internal variables... can anyone explain this seemingly anomolous
> > event to me?
>
> Why would it get read into internal variables? In the code above you
> never tell it to. Perhaps you meant:
>
> function db() {
> global $db;
> $this->user = $db['user'];
> $this->pass = $db['pass'];
>
> }
>
> Although I would add that you shouldn't really do this. It would be
> preferable to do something like this instead:
>
> function db($user, $pass) {
> $this->user = $user;
> $this->pass = $pass;
>
> }
>
> And pass in the values appropriately when you instantiate the object.- Hide quoted text -
>
> - Show quoted text -
I left out the rest of the rest of the initialization code for
brevity. But you're right it would be more appropriate to do that.
However, it still eludes me why I am not able to import that variable
using the global operator. I was able to circumvent this by using the
$GLOBALS array but that in itself is bad practice.
I've changed the code since then to use default initializers in the
constructor for a default setting, but just out of curiousity and
pedagogical reasons, why is this happening ?!
Navigation:
[Reply to this message]
|