You are here: Re: the global key word « PHP Programming Language « IT news, forums, messages
Re: the global key word

Posted by ZeldorBlat on 06/26/07 13:11

On Jun 26, 2:21 am, Manny <thebar...@gmail.com> wrote:
> 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 ?!

It's difficult to say since you haven't (according to you) included
all the code from the constructor.

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация