You are here: Re: [PHP] define (true/false) « PHP « IT news, forums, messages
Re: [PHP] define (true/false)

Posted by Jochem Maas on 10/21/79 11:22

Sebastian wrote:
> i never really used constants before so this may sound stupid..

you could use constants and still sound stupid.
- that would be 'constantly sounding stupid' ;-)

> when you define a constant using define() and want to return true/false
> is this logical:

yes, if a little verbose ...

>
> if($bars == 3)
> {
> define('BAR', 1);
> }
>
> then:
>
> if(BAR)
> {
> // bars is true
> }
>
> or should i need to do an else statement as well:
>
> if($bars == 3)
> {
> define('BAR', 1);
> }
> else
> {
> define('BAR', 0)
> }

I _think_ you want to define BAR in both cases (but you may not
- bare in mind that its also valid to conditionally define a constant
and have other code act depending on whether the constant exists by way
of the defined() function.). but 8 lines of code to define a single constants
seems a little wastful (I find that the better my programming skills the
more dense my code becomes - I like to be able to fit as much code as is
possible, without making it ugly or unreadable, on screen) ....
to that end here is another way to write the example above.

// 'normal'
define('BAR', ($bars == 3));
// 'a bit anal'
define('BAR', ($bars === 3));
// OTT
define('BAR', (boolean)($bars === 3));

essentially, if you want BAR to act as a true/false flag
(e.g.: if (BAR) {/* go to the bar */} ) it does not really matter if
you use 1/0 or true/false but I would recommend using the boolean
values.

>
> lastly is it more practical to just do:
>
> if($bars == 3)
> {
> $bar = true;

$bar _could_ be changed (or unset) somewhere else in the code,
and is only available in the scope that it is defined
in (e.g. a function) where as a constant once defined
cannot change or be unset and is available everywhere. People
often use constants to give meaningful names to values which
would otherwise be hard to remember - to that end constants are
defined by php itself ... and also quite a few extensions ...
take for instance these:

IMG_GIF
IMG_JPG
IMG_JPEG (same as IMG_JPG)
IMG_PNG

which are alot easier to work with than:

1,
2,
4

try the following line:

<? var_dump( IMG_GIF, IMG_JPG, IMG_PNG ); ?>


> }
>
> i am curious what most people would use.
>
>

 

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

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