473,467 Members | 1,596 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Macros in php

Is there any hope that new versions of PHP
will support macros similar to C or C++?
I've searched manual and didn't find anything
except define directive, but it can be used
to define constant values only.
Of course it is not THAT neccessary functionality,
but it could be very useful.

greetz Emil
Apr 7 '06 #1
47 32844
"Emil" <em**************@podczta.onet.pl> wrote in message
news:e1**********@news.onet.pl...
Is there any hope that new versions of PHP
will support macros similar to C or C++?
I've searched manual and didn't find anything
except define directive, but it can be used
to define constant values only.
Of course it is not THAT neccessary functionality,
but it could be very useful.

What's the actual difference between a function and a macro? How would use
of macros differ from functions?

Let's pretend there is a way of defining a macro in php...
define ("MAX($a,$b)", "(($a<$b)?$b:$a)");

vs.

function max( $a, $b ) {
return $a < $b ? $b : $a;
}

And use them like this:
MAX($a,$b); // This is macro, so much easier!
max($a,$b); // This is plain old dull function! Bah, no no, not like
this...

I mean.... WTF?

--
"ohjelmoija on organismi joka muuttaa kofeiinia koodiksi" -lpk
sp**@outolempi.net | Gedoon-S @ IRCnet | rot13(xv***@bhgbyrzcv.arg)
Apr 7 '06 #2
Kimmo Laine wrote:
"Emil" <em**************@podczta.onet.pl> wrote in message
news:e1**********@news.onet.pl...
Is there any hope that new versions of PHP
will support macros similar to C or C++?
I've searched manual and didn't find anything
except define directive, but it can be used
to define constant values only.
Of course it is not THAT neccessary functionality,
but it could be very useful.


What's the actual difference between a function and a macro? How would use
of macros differ from functions?

Let's pretend there is a way of defining a macro in php...
define ("MAX($a,$b)", "(($a<$b)?$b:$a)");

vs.

function max( $a, $b ) {
return $a < $b ? $b : $a;
}

And use them like this:
MAX($a,$b); // This is macro, so much easier!
max($a,$b); // This is plain old dull function! Bah, no no, not like
this...

I mean.... WTF?


Macros are more efficient.

Personally, one construct I use heavily and would like to replace with a macro:

$var = isset($_POST['postvar']) ? $_POST['postvar'] . 'default value';

I use something similar for a get/post, session and cookie values. It would be
very nice to have a macro.

--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attglobal.net
==================
Apr 7 '06 #3
"Jerry Stuckle" <js*******@attglobal.net> wrote in message
news:GL******************************@comcast.com. ..
Kimmo Laine wrote:
"Emil" <em**************@podczta.onet.pl> wrote in message
news:e1**********@news.onet.pl...
Is there any hope that new versions of PHP
will support macros similar to C or C++?
I've searched manual and didn't find anything
except define directive, but it can be used
to define constant values only.
Of course it is not THAT neccessary functionality,
but it could be very useful.


What's the actual difference between a function and a macro? How would
use of macros differ from functions?

Let's pretend there is a way of defining a macro in php...
define ("MAX($a,$b)", "(($a<$b)?$b:$a)");

vs.

function max( $a, $b ) {
return $a < $b ? $b : $a;
}

And use them like this:
MAX($a,$b); // This is macro, so much easier!
max($a,$b); // This is plain old dull function! Bah, no no, not like
this...

I mean.... WTF?


Macros are more efficient.

Personally, one construct I use heavily and would like to replace with a
macro:

$var = isset($_POST['postvar']) ? $_POST['postvar'] . 'default value';

I use something similar for a get/post, session and cookie values. It
would be very nice to have a macro.

And tell mme again why you couldn't write a function instead of a macro to
do that?

Just so we all remember what we're talking about here... In C a macro is a
syntax replacement that the precompiler uses to both optimize the code
(avoid the unnecessary function jump for a short task) and make it easy to
write for the coder. The complier simply translates a pseudo code (the
macro) to actual code when the code is compiled to executable. Since PHP is
not precompiled, I don't see how this could be of any use. The php source
code should be precompiled in order to get the replaced... Macros just don't
have a purpouse in run-time compiled language like they do in precompiled
languages.

--
"ohjelmoija on organismi joka muuttaa kofeiinia koodiksi" -lpk
sp**@outolempi.net | Gedoon-S @ IRCnet | rot13(xv***@bhgbyrzcv.arg)
Apr 7 '06 #4
Kimmo Laine wrote:
"Jerry Stuckle" <js*******@attglobal.net> wrote in message
news:GL******************************@comcast.com. ..
Kimmo Laine wrote:
"Emil" <em**************@podczta.onet.pl> wrote in message
news:e1**********@news.onet.pl...
Is there any hope that new versions of PHP
will support macros similar to C or C++?
I've searched manual and didn't find anything
except define directive, but it can be used
to define constant values only.
Of course it is not THAT neccessary functionality,
but it could be very useful.


What's the actual difference between a function and a macro? How would
use of macros differ from functions?

Let's pretend there is a way of defining a macro in php...
define ("MAX($a,$b)", "(($a<$b)?$b:$a)");

vs.

function max( $a, $b ) {
return $a < $b ? $b : $a;
}

And use them like this:
MAX($a,$b); // This is macro, so much easier!
max($a,$b); // This is plain old dull function! Bah, no no, not like
this...

I mean.... WTF?


Macros are more efficient.

Personally, one construct I use heavily and would like to replace with a
macro:

$var = isset($_POST['postvar']) ? $_POST['postvar'] . 'default value';

I use something similar for a get/post, session and cookie values. It
would be very nice to have a macro.


And tell mme again why you couldn't write a function instead of a macro to
do that?

Just so we all remember what we're talking about here... In C a macro is a
syntax replacement that the precompiler uses to both optimize the code
(avoid the unnecessary function jump for a short task) and make it easy to
write for the coder. The complier simply translates a pseudo code (the
macro) to actual code when the code is compiled to executable. Since PHP is
not precompiled, I don't see how this could be of any use. The php source
code should be precompiled in order to get the replaced... Macros just don't
have a purpouse in run-time compiled language like they do in precompiled
languages.


I know exactly what a macro is in C - I've been programming C for over 20 years.

And yes, the can still be more efficient in PHP. Remember - each page is NOT
reparsed every time it is requested. PHP can also cache pages, then pull the
code right from the cache.

So yes, they can be more efficient.

--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attglobal.net
==================
Apr 7 '06 #5
Kimmo Laine napisał(a):
$var = isset($_POST['postvar']) ? $_POST['postvar'] . 'default value';

I have the same problem.

And tell mme again why you couldn't write a function instead of a macro to
do that?


The reason is when you pass $_POST['postvar'] to a function and
$_POST['postvar'] is not set, PHP generates warning. Of course one could
turn off warnings and usually does, but in my opinion it's not a
solution. However checking everytime if variable (or array index) is set
before passing it to a function generates sometimes tones of similar
code which could be simply replaced with one elegant macro.
Maybe it's just a matter of programmer's habit, I feel lack of macros.

Greetz Emil
Apr 7 '06 #6
"Kimmo Laine" <sp**@outolempi.net> writes:
"Emil" <em**************@podczta.onet.pl> wrote in message
news:e1**********@news.onet.pl...
Is there any hope that new versions of PHP
will support macros similar to C or C++?
I've searched manual and didn't find anything
except define directive, but it can be used
to define constant values only.
Of course it is not THAT neccessary functionality,
but it could be very useful.

What's the actual difference between a function and a macro? How would use
of macros differ from functions?


Just the other day, I was thinking that a preprocessor in PHP would be
handy. I've got a lot of code that goes

<?php
include 'cache.inc';
$c = new cache;
if ($c->uncached()) {

... main body of php code

}
$c->end(); // cache and/or display html
include 'stats_counter.inc';
?>

It would be nice to replace this with

<?php
START_CACHING;

... main body of php code

END_CACHING;
?>

but I can't see how this can be done neatly[*] with functions.
Ian

[*] It could be done badly with cache.php?inc=mycode.php where
cache.php is something like

<?php
include 'cache.inc';
$c = new cache;
if ($c->uncached()) {

include $_GET['inc'];

}
$c->end(); // cache and/or display html
include 'stats_counter.inc';
?>
Apr 7 '06 #7
Jerry Stuckle wrote:
Macros are more efficient.

Personally, one construct I use heavily and would like to replace with a macro:

$var = isset($_POST['postvar']) ? $_POST['postvar'] . 'default value';

I use something similar for a get/post, session and cookie values. It would be
very nice to have a macro.


I think the operation is common enough that it deserves a function-like
operator. Something like

$val = coalesce($_POST['postvar'], $_SESSION['postvar'], 'default
value');

Apr 7 '06 #8
"Ian McConnell" <ia*@emit.demon.co.uk> wrote in message
news:87************@emit.demon.co.uk...
Just the other day, I was thinking that a preprocessor in PHP would be
handy. I've got a lot of code that goes

<?php
include 'cache.inc';
$c = new cache;
if ($c->uncached()) {

... main body of php code

}
$c->end(); // cache and/or display html
include 'stats_counter.inc';
?>

It would be nice to replace this with

<?php
START_CACHING;

... main body of php code

END_CACHING;
?>


Any piece of software is essentially a series of mental concepts, written
down as computer code. So what you are saying (and I agree heartily) is:
See this series of PHP statements? They represent a concept called "Start
Caching".

So it makes sense to write START_CACHING rather than spell out the details.
I think it makes the code easier to read, both for the author and any other
soul who has to learn it.

This aspect of macros has nothing to do with computer efficiency, but a
great deal to do with human efficiency. We *like* to name things.
Languages should accomodate this.

What's nice about macros is that they can be used to name rather arbitrary
stuff, including fragments of code. Functions have a different role to
play.

-Dana
Apr 7 '06 #9
> What's the actual difference between a function and a macro? How would use
of macros differ from functions?


I was working on modular system, where every module was a file with
object definition.

I needed to make some global variables accessible in method of this
object (i.e. database connection object) in every module, but I wanted
to have a list of these variables only once in whole system (it would be
unpleasant to edit all modules if I decided to, for example, change name
of any of these variables).

Function is useless in this case, so I needed a macro.

I solved a problem this way:

// In initialisation part of code
define('MY_MACRO', 'global $database, $global_config,
$any_other_needed_variables;');

// In beginning of module object's method
eval (MY_MACRO);

But maybe there is much better way to do this
Apr 7 '06 #10
>> Macros are more efficient.

Anyone got actual PROOF that macros are more efficient in an
interpreted language? Claims that <language construct x> is
more efficient without specifying the language are almost always
false.
Personally, one construct I use heavily and would like to replace with a
macro:

$var = isset($_POST['postvar']) ? $_POST['postvar'] . 'default value';

I use something similar for a get/post, session and cookie values. It
would be very nice to have a macro.

And tell mme again why you couldn't write a function instead of a macro to
do that?


Let's see you implement the equivalent of the C macros:

#define LENGTH (
#define FEET ) * 12.0 + (
#define INCHES )

used as:
LENGTH 6 FEET 3 INCHES

in a PHP function. Of course, abusing C macros like that should carry
the death penalty.

Gordon L. Burditt
Apr 7 '06 #11
Kimmo Laine wrote:
"Emil" <em**************@podczta.onet.pl> wrote in message
news:e1**********@news.onet.pl...
Is there any hope that new versions of PHP
will support macros similar to C or C++?
What's the actual difference between a function and a macro? How would use
of macros differ from functions?

Let's pretend there is a way of defining a macro in php...
define ("MAX($a,$b)", "(($a<$b)?$b:$a)");

vs.

function max( $a, $b ) {
return $a < $b ? $b : $a;
}


The difference is that macros are applied as text substitution before
parsing is carried out. This means that macros can carry out
substitutions on the code that would not in itself be a valid language
construct.

The classic example of misuse of this sort of technique in C is

#define BEGIN {
#define END }

then you can do silly things like:

for (i = 0; i < 10; i++)
BEGIN
printf("%d\n", i);
END

Used judiciously these sorts of techniques can open up all sorts of
possibilities (I've seen generic type containers implemented in pure C
using macros), but the general consensus is that the potential for
misuse is far too great and modern language constructs have obviated all
the genuine needs for such techniques.

To the OP: What are you trying to achieve with macros? With a
combination of pass-by-reference, soft references and eval() you can
achieve many of the things that C macros are able to achieve, with
better syntax and less potential for misuse.

Tim
*** Free account sponsored by SecureIX.com ***
*** Encrypt your Internet usage with a free VPN account from http://www.SecureIX.com ***
Apr 8 '06 #12
Emil wrote:
Kimmo Laine napisał(a):
$var = isset($_POST['postvar']) ? $_POST['postvar'] . 'default value';


I have the same problem.

And tell mme again why you couldn't write a function instead of a
macro to do that?


The reason is when you pass $_POST['postvar'] to a function and
$_POST['postvar'] is not set, PHP generates warning. Of course one could
turn off warnings and usually does, but in my opinion it's not a
solution.


Surely $_POST is a superglobal and will thus be available within the
function scope just as it would be within the macro "scope".

Couldn't you do something like this (untested code, function name is
deliberately bad)?

function get_post_var_with_default($name, $default = 'default value')
{
if (isset($_POST[$name]))
{
return $_POST[$name];
}
else
{
return $default;
}
}

then later

$var = get_post_var_with_default('postvar');

Am I missing something here?

Tim
*** Free account sponsored by SecureIX.com ***
*** Encrypt your Internet usage with a free VPN account from http://www.SecureIX.com ***
Apr 8 '06 #13
Gordon Burditt wrote:
Macros are more efficient.


Anyone got actual PROOF that macros are more efficient in an
interpreted language? Claims that <language construct x> is
more efficient without specifying the language are almost always
false.


Do any widely used interpreted languages implement C-style macros? (I'm
aware of Lisp, but Lisp macros are quite different from C macros).

If not, it's even worse than arguing about efficency of macros in an
unspecified language, we're arguing about efficiency of macros in a
*hypothetical* language.

Tim
*** Free account sponsored by SecureIX.com ***
*** Encrypt your Internet usage with a free VPN account from http://www.SecureIX.com ***
Apr 8 '06 #14
Tim Martin wrote:
Emil wrote:
Kimmo Laine napisał(a):
$var = isset($_POST['postvar']) ? $_POST['postvar'] . 'default
value';


I have the same problem.


And tell mme again why you couldn't write a function instead of a
macro to do that?

The reason is when you pass $_POST['postvar'] to a function and
$_POST['postvar'] is not set, PHP generates warning. Of course one
could turn off warnings and usually does, but in my opinion it's not a
solution.

Surely $_POST is a superglobal and will thus be available within the
function scope just as it would be within the macro "scope".

Couldn't you do something like this (untested code, function name is
deliberately bad)?

function get_post_var_with_default($name, $default = 'default value')
{
if (isset($_POST[$name]))
{
return $_POST[$name];
}
else
{
return $default;
}
}

then later

$var = get_post_var_with_default('postvar');

Am I missing something here?

Tim
*** Free account sponsored by SecureIX.com ***
*** Encrypt your Internet usage with a free VPN account from
http://www.SecureIX.com ***


And you'd need another one for $_SESSION, and another one for $_GET.....

And what if you want to do it for a non-super global - i.e. an array member?

With macros you need only one, i.e.

$var = GET_WITH_DEFAULT($_POST['myvar']), 'default value');
$var2 = GET_WITH_DEFAULT_VALUE($myarray['test'], 'default_value);
--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attglobal.net
==================
Apr 8 '06 #15
Tim Martin wrote:
Kimmo Laine wrote:
"Emil" <em**************@podczta.onet.pl> wrote in message
news:e1**********@news.onet.pl...
Is there any hope that new versions of PHP
will support macros similar to C or C++?

What's the actual difference between a function and a macro? How would
use of macros differ from functions?

Let's pretend there is a way of defining a macro in php...
define ("MAX($a,$b)", "(($a<$b)?$b:$a)");

vs.

function max( $a, $b ) {
return $a < $b ? $b : $a;
}

The difference is that macros are applied as text substitution before
parsing is carried out. This means that macros can carry out
substitutions on the code that would not in itself be a valid language
construct.

The classic example of misuse of this sort of technique in C is

#define BEGIN {
#define END }

then you can do silly things like:

for (i = 0; i < 10; i++)
BEGIN
printf("%d\n", i);
END

Used judiciously these sorts of techniques can open up all sorts of
possibilities (I've seen generic type containers implemented in pure C
using macros), but the general consensus is that the potential for
misuse is far too great and modern language constructs have obviated all
the genuine needs for such techniques.


What "General consensus"? I haven't heard that.

In fact, quite the opposite. I've heard more people wish there were C/C++ type
macros in other languages.

And just because someone might misuse them means no one can have them? People
might misuse functions - get rid of them. Someone might misuse relational
databases - get rid of them.

It's not a valid argument.

To the OP: What are you trying to achieve with macros? With a
combination of pass-by-reference, soft references and eval() you can
achieve many of the things that C macros are able to achieve, with
better syntax and less potential for misuse.

Make code clearer, more concise and more maintainable. All of which can be
increased by the judicious use of macros.
Tim
*** Free account sponsored by SecureIX.com ***
*** Encrypt your Internet usage with a free VPN account from
http://www.SecureIX.com ***

--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attglobal.net
==================
Apr 8 '06 #16
Jerry Stuckle said the following on 08/04/2006 16:11:
Tim Martin wrote:

function get_post_var_with_default($name, $default = 'default value')
{
if (isset($_POST[$name]))
{
return $_POST[$name];
}
else
{
return $default;
}
}

then later

$var = get_post_var_with_default('postvar');

Am I missing something here?

And you'd need another one for $_SESSION, and another one for $_GET.....

And what if you want to do it for a non-super global - i.e. an array
member?

With macros you need only one, i.e.

$var = GET_WITH_DEFAULT($_POST['myvar']), 'default value');
$var2 = GET_WITH_DEFAULT_VALUE($myarray['test'], 'default_value);

function getWithDefault(&$array, $key, $default = NULL)
{
return (isset($array[$key])) ? $array[$key] : $default;
}
--
Oli
Apr 8 '06 #17
Tim Martin wrote:
Kimmo Laine wrote:
"Emil" <em**************@podczta.onet.pl> wrote in message
news:e1**********@news.onet.pl...
Is there any hope that new versions of PHP
will support macros similar to C or C++?
What's the actual difference between a function and a macro? How would
use of macros differ from functions?

Let's pretend there is a way of defining a macro in php...
define ("MAX($a,$b)", "(($a<$b)?$b:$a)");

vs.

function max( $a, $b ) {
return $a < $b ? $b : $a;
}


The difference is that macros are applied as text substitution before
parsing is carried out. This means that macros can carry out
substitutions on the code that would not in itself be a valid language
construct.


Beside possibility to create funny constructs, the difference between
function and macro both implementing same code is, that macro will
expand the code inline but function will create a call. Macro give the
benefit of faster execution for the penalty of more code. Function gives
the benefit of smaller code for the penalty of slower execution.

in C/C++ macros can also beter optimise with surrounding code, although
function usually does not ake any assumtions about register content,
will not fold constants (e.g. x=5+MAX(3,6) will fold into x=11, but not
so with the function call).

In PHP every function call has to switch context, initialise local
variables, which in C is done with few instructions (on x86 is either
ENTER or PUSH EBP, MOV EBP, ESP, ADD ESP,frame), but in PHP carries
little more everhead.
To the OP: What are you trying to achieve with macros? With a
combination of pass-by-reference, soft references and eval() you can
achieve many of the things that C macros are able to achieve, with
better syntax and less potential for misuse.


I agree, PHP is a text processor itself. Just to make a point here is an
example of incomplete macro expansion implementation in PHP, which would
be almost impossible in C:

function ExpandMacros(path,macros)
{
text = get_file_content(path);

// expand'em - skipped

put_file_content(path.'.expanded',
'define(\'EXPANDED\', 1);\n\n' . text);
}

@include __FILE__.'.expanded"

if(!EXPANDED)
{
ExpandMacros(__FILE__, array(/* macros definitions */) )
return;
}

For brewity reason, I did not go into the details of expanding macros.

Roman
Apr 8 '06 #18

Roman Ziak wrote:

function ExpandMacros(path,macros)
{
text = get_file_content(path);

// expand'em - skipped

put_file_content(path.'.expanded',
'define(\'EXPANDED\', 1);\n\n' . text);
}

@include __FILE__.'.expanded"

if(!EXPANDED)
{
ExpandMacros(__FILE__, array(/* macros definitions */) )
return;
}


The above example is wrong and is a mixture of C and PHP.

This one is working:

<?php

@include __FILE__.'.expanded';

if(1 != EXPANDED)
{
// this function should be elsewhere

function ExpandMacros($path)
{
$text = file_get_contents($path);

// expand'em - skipped
$text = str_replace('MAX', '120', $text);

// strip expansion stub
$pos = strpos($text, '// ' . 'CODE BEGIN');
$text = "<?php\n\ndefine('EXPANDED',1);\n\n" . substr($text, $pos);

file_put_contents($path.'.expanded', $text);
}

ExpandMacros(__FILE__);

require __FILE__ . '.expanded';

return;
}

// CODE BEGIN

echo MAX;

?>

Apr 8 '06 #19
Roman Ziak wrote:
Tim Martin wrote:
Kimmo Laine wrote:
"Emil" <em**************@podczta.onet.pl> wrote in message
news:e1**********@news.onet.pl...

Is there any hope that new versions of PHP
will support macros similar to C or C++?
What's the actual difference between a function and a macro? How would
use of macros differ from functions?

Let's pretend there is a way of defining a macro in php...
define ("MAX($a,$b)", "(($a<$b)?$b:$a)");

vs.

function max( $a, $b ) {
return $a < $b ? $b : $a;
}


The difference is that macros are applied as text substitution before
parsing is carried out. This means that macros can carry out
substitutions on the code that would not in itself be a valid language
construct.

Beside possibility to create funny constructs, the difference between
function and macro both implementing same code is, that macro will
expand the code inline but function will create a call. Macro give the
benefit of faster execution for the penalty of more code. Function gives
the benefit of smaller code for the penalty of slower execution.

In addition, you get the current context. When you have to do something
complex two or more times in code, either your function has the
parameter list from hell or it contains a (set of) global statement from
hell, either of which lead to maintenance nightmares and coding errors,
especially since php is not (strongly) type checked. in C/C++ macros can also beter optimise with surrounding code, although
function usually does not ake any assumtions about register content,
will not fold constants (e.g. x=5+MAX(3,6) will fold into x=11, but not
so with the function call).

In PHP every function call has to switch context, initialise local
variables, which in C is done with few instructions (on x86 is either
ENTER or PUSH EBP, MOV EBP, ESP, ADD ESP,frame), but in PHP carries
little more everhead.

To the OP: What are you trying to achieve with macros? With a
combination of pass-by-reference, soft references and eval() you can
achieve many of the things that C macros are able to achieve, with
better syntax and less potential for misuse.

I agree, PHP is a text processor itself. Just to make a point here is an
example of incomplete macro expansion implementation in PHP, which would
be almost impossible in C:

function ExpandMacros(path,macros)
{
text = get_file_content(path);

// expand'em - skipped

put_file_content(path.'.expanded',
'define(\'EXPANDED\', 1);\n\n' . text);
}

@include __FILE__.'.expanded"

if(!EXPANDED)
{
ExpandMacros(__FILE__, array(/* macros definitions */) )
return;
}

For brewity reason, I did not go into the details of expanding macros.

The m4 macro processor, for instance, would do the job. Roman

Apr 8 '06 #20
Tim Martin wrote:
Used judiciously these sorts of techniques can open up all sorts of
possibilities (I've seen generic type containers implemented in pure C
using macros), but the general consensus is that the potential for
misuse is far too great and modern language constructs have obviated all
the genuine needs for such techniques.


Personally I really dislike this brief in the CS circle that somehow
programmers need to be saved from themselves. It arises from the same
elitist, I-know-what's-best-for-you mentality prevalent in academia.
More than just a tool, these ivory tower geeks want a computer language
to enforce their values and way of thinking.

[end of rant]

C style preprocessing could come in very handy in solving compatibility
issues. Anyone who has had to get a PHP5 class to work in PHP 4 knows
what I mean. A couple #define's would have taken care of the syntatical
differences, which can now only be resolved with some ugly eval()
statements.

Apr 8 '06 #21
Oli Filth wrote:
Jerry Stuckle said the following on 08/04/2006 16:11:
Tim Martin wrote:

function get_post_var_with_default($name, $default = 'default value')
{
if (isset($_POST[$name]))
{
return $_POST[$name];
}
else
{
return $default;
}
}

then later

$var = get_post_var_with_default('postvar');

Am I missing something here?

> And you'd need another one for $_SESSION, and another one for $_GET.....


And what if you want to do it for a non-super global - i.e. an array
member?

With macros you need only one, i.e.

$var = GET_WITH_DEFAULT($_POST['myvar']), 'default value');
$var2 = GET_WITH_DEFAULT_VALUE($myarray['test'], 'default_value);

function getWithDefault(&$array, $key, $default = NULL)
{
return (isset($array[$key])) ? $array[$key] : $default;
}


And if $array is empty you get a warning.
--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attglobal.net
==================
Apr 8 '06 #22
Jerry Stuckle said the following on 08/04/2006 21:51:
Oli Filth wrote:
function getWithDefault(&$array, $key, $default = NULL)
{
return (isset($array[$key])) ? $array[$key] : $default;
}


And if $array is empty you get a warning.


You do? I don't. Nor can I see any reason why one should get a
warning. What version of PHP are you running?
--
Oli
Apr 8 '06 #23
Oli Filth wrote:
Jerry Stuckle said the following on 08/04/2006 21:51:
Oli Filth wrote:
function getWithDefault(&$array, $key, $default = NULL)
{
return (isset($array[$key])) ? $array[$key] : $default;
}


And if $array is empty you get a warning.


You do? I don't. Nor can I see any reason why one should get a
warning. What version of PHP are you running?


Try turning on all warnings.

--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attglobal.net
==================
Apr 9 '06 #24
Jerry Stuckle said the following on 09/04/2006 02:53:
Oli Filth wrote:
Jerry Stuckle said the following on 08/04/2006 21:51:
Oli Filth wrote:

function getWithDefault(&$array, $key, $default = NULL)
{
return (isset($array[$key])) ? $array[$key] : $default;
}

And if $array is empty you get a warning.


You do? I don't. Nor can I see any reason why one should get a
warning. What version of PHP are you running?


Try turning on all warnings.

I have error level set to E_ALL | E_STRICT. The following code executes
fine:
<?php

function getValueWithDefault(&$array, $key, $default = NULL)
{
return (isset($array[$key])) ? $array[$key] : $default;
}

$var = array();
echo getValueWithDefault($var, "Roger", "Dodger") . "\n";

?>

I see no reason why an error/warning should get thrown. isset() simply
looks for an element with the specified key name in the associative
array. In an empty array, the key doesn't exist, so isset() returns false.

--
Oli
Apr 9 '06 #25
Oli Filth wrote:
Jerry Stuckle said the following on 09/04/2006 02:53:
Oli Filth wrote:
Jerry Stuckle said the following on 08/04/2006 21:51:

Oli Filth wrote:

> function getWithDefault(&$array, $key, $default = NULL)
> {
> return (isset($array[$key])) ? $array[$key] : $default;
> }
>
>

And if $array is empty you get a warning.
You do? I don't. Nor can I see any reason why one should get a
warning. What version of PHP are you running?


Try turning on all warnings.


I have error level set to E_ALL | E_STRICT. The following code executes
fine:
<?php

function getValueWithDefault(&$array, $key, $default = NULL)
{
return (isset($array[$key])) ? $array[$key] : $default;
}

$var = array();
echo getValueWithDefault($var, "Roger", "Dodger") . "\n";

?>

I see no reason why an error/warning should get thrown. isset() simply
looks for an element with the specified key name in the associative
array. In an empty array, the key doesn't exist, so isset() returns false.

That's not what I said. I said if $var is EMPTY.

Take out the $var=array() line and see what you get.
--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attglobal.net
==================
Apr 9 '06 #26
Jerry Stuckle said the following on 09/04/2006 06:14:
Oli Filth wrote:
I have error level set to E_ALL | E_STRICT. The following code
executes fine:
<?php

function getValueWithDefault(&$array, $key, $default = NULL)
{
return (isset($array[$key])) ? $array[$key] : $default;
}

$var = array();
echo getValueWithDefault($var, "Roger", "Dodger") . "\n";

?>

I see no reason why an error/warning should get thrown. isset()
simply looks for an element with the specified key name in the
associative array. In an empty array, the key doesn't exist, so
isset() returns false.

That's not what I said. I said if $var is EMPTY.


From the PHP manual for empty():

"The following things are considered to be empty:
...
array() (an empty array)
..."

Take out the $var=array() line and see what you get.


So you mean "undefined"? Going back to the original purpose of this
function/macro, why would you ever want to call it on an undefined array?

But anyway, removing the $var = array() line does not result in any
error/warning. Because it's being passed by reference, PHP
automatically creates a variable $var in the global scope (because for
all it knows, this could be an output argument for the function).
--
Oli
Apr 9 '06 #27
Oli Filth said the following on 09/04/2006 13:44:
Jerry Stuckle said the following on 09/04/2006 06:14:
Oli Filth wrote:
I have error level set to E_ALL | E_STRICT. The following code
executes fine:
<?php

function getValueWithDefault(&$array, $key, $default = NULL)
{
return (isset($array[$key])) ? $array[$key] : $default;
}

$var = array();
echo getValueWithDefault($var, "Roger", "Dodger") . "\n";

?>

Take out the $var=array() line and see what you get.


But anyway, removing the $var = array() line does not result in any
error/warning. Because it's being passed by reference, PHP
automatically creates a variable $var in the global scope


That should be *caller* scope...
--
Oli
Apr 9 '06 #28
Oli Filth wrote:
Jerry Stuckle said the following on 09/04/2006 06:14:
Oli Filth wrote:
I have error level set to E_ALL | E_STRICT. The following code
executes fine:
<?php

function getValueWithDefault(&$array, $key, $default = NULL)
{
return (isset($array[$key])) ? $array[$key] : $default;
}

$var = array();
echo getValueWithDefault($var, "Roger", "Dodger") . "\n";

?>

I see no reason why an error/warning should get thrown. isset()
simply looks for an element with the specified key name in the
associative array. In an empty array, the key doesn't exist, so
isset() returns false.

That's not what I said. I said if $var is EMPTY.

From the PHP manual for empty():

"The following things are considered to be empty:
...
array() (an empty array)
..."


Yes, the array is empty. But $var is not! It contains an empty array.

Two different things.
Take out the $var=array() line and see what you get.

So you mean "undefined"? Going back to the original purpose of this
function/macro, why would you ever want to call it on an undefined array?


Because it may or may not exist, that's why.
But anyway, removing the $var = array() line does not result in any
error/warning. Because it's being passed by reference, PHP
automatically creates a variable $var in the global scope (because for
all it knows, this could be an output argument for the function).


Yep, and now you have changed the variable, haven't you?

--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attglobal.net
==================
Apr 9 '06 #29
Oli Filth wrote:
Oli Filth said the following on 09/04/2006 13:44:
Jerry Stuckle said the following on 09/04/2006 06:14:
Oli Filth wrote:

I have error level set to E_ALL | E_STRICT. The following code
executes fine:
<?php

function getValueWithDefault(&$array, $key, $default = NULL)
{
return (isset($array[$key])) ? $array[$key] : $default;
}

$var = array();
echo getValueWithDefault($var, "Roger", "Dodger") . "\n";

?>

Take out the $var=array() line and see what you get.

But anyway, removing the $var = array() line does not result in any
error/warning. Because it's being passed by reference, PHP
automatically creates a variable $var in the global scope

That should be *caller* scope...


OK, you want to argue with everyone who supports the idea of macros. Fine.
Let's see you to this as easily and as cleanly without macros:

define('FOREACH(X, K, V)', 'if (isset(X) && isarray(X)) foreach(X as K=>V)
FOREACH($var,$key,$value) {

// Process data in $key=>$value here.
}

FOREACH($var2, $key2, $value2) {
// Different processing of $key2=>value2 here
}
--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attglobal.net
==================
Apr 9 '06 #30
Jerry Stuckle wrote:
Oli Filth wrote:
Jerry Stuckle said the following on 09/04/2006 06:14:
Oli Filth wrote:

I have error level set to E_ALL | E_STRICT. The following code
executes fine:
<?php

function getValueWithDefault(&$array, $key, $default = NULL)
{
return (isset($array[$key])) ? $array[$key] : $default;
}

$var = array();
echo getValueWithDefault($var, "Roger", "Dodger") . "\n";

?>

I see no reason why an error/warning should get thrown. isset()
simply looks for an element with the specified key name in the
associative array. In an empty array, the key doesn't exist, so
isset() returns false.
That's not what I said. I said if $var is EMPTY.

From the PHP manual for empty():

"The following things are considered to be empty:
...
array() (an empty array)
..."


Yes, the array is empty. But $var is not! It contains an empty array.


No, $var doesn't *contain* an empty array, $var *is* an empty array.

<?php
$var = array();
echo empty($var) ? "TRUE" : "FALSE"; // echoes "TRUE"
?>

Take out the $var=array() line and see what you get.


So you mean "undefined"? Going back to the original purpose of this
function/macro, why would you ever want to call it on an undefined array?

Because it may or may not exist, that's why.


I thought the purpose was to check for the existence of an *entry* in
an associative array, such as $_POST, etc.

On the other hand, checking for the existence of a *variable* implies
bad practice. There should be no need. You should always know a
priori what variables exist at any given point in your code (assuming
the wonders of register_globals are disabled).

But anyway, removing the $var = array() line does not result in any
error/warning. Because it's being passed by reference, PHP
automatically creates a variable $var in the global scope (because for
all it knows, this could be an output argument for the function).


Yep, and now you have changed the variable, haven't you?


Only if it was undefined in the first place, which would be bad
practice.

--
Oli

Apr 9 '06 #31
Jerry Stuckle wrote:
Oli Filth wrote:
Oli Filth said the following on 09/04/2006 13:44:
Jerry Stuckle said the following on 09/04/2006 06:14:
Oli Filth wrote:

> <?php
>
> function getValueWithDefault(&$array, $key, $default = NULL)
> {
> return (isset($array[$key])) ? $array[$key] : $default;
> }
>
> $var = array();
> echo getValueWithDefault($var, "Roger", "Dodger") . "\n";
>
> ?>

Take out the $var=array() line and see what you get.

But anyway, removing the $var = array() line does not result in any
error/warning. Because it's being passed by reference, PHP
automatically creates a variable $var in the global scope
That should be *caller* scope...


OK, you want to argue with everyone who supports the idea of macros. Fine.


Woah, easy there tiger! Did I at any point say, or even imply, that
macros were a bad idea? No.

All I've done so far is correct your claim that one couldn't do the
getValueWithDefault thing without a macro.

I'm a C/C++ programmer at heart, I use macros there, and I know the
benefits (and otherwise) of them.

Let's see you to this as easily and as cleanly without macros:

define('FOREACH(X, K, V)', 'if (isset(X) && isarray(X)) foreach(X as K=>V)
FOREACH($var,$key,$value) {

// Process data in $key=>$value here.
}

FOREACH($var2, $key2, $value2) {
// Different processing of $key2=>value2 here
}


Again, that just implies bad practice. You should always know whether
a *variable* exists, and as such, should have no reason to call isset()
on it.
--
Oli

Apr 9 '06 #32
Oli Filth wrote:
Jerry Stuckle wrote:
Oli Filth wrote:
Oli Filth said the following on 09/04/2006 13:44:

Jerry Stuckle said the following on 09/04/2006 06:14:

>Oli Filth wrote:
>
>
>> <?php
>>
>> function getValueWithDefault(&$array, $key, $default = NULL)
>> {
>> return (isset($array[$key])) ? $array[$key] : $default;
>> }
>>
>> $var = array();
>> echo getValueWithDefault($var, "Roger", "Dodger") . "\n";
>>
>> ?>
>
>Take out the $var=array() line and see what you get.

But anyway, removing the $var = array() line does not result in any
error/warning. Because it's being passed by reference, PHP
automatically creates a variable $var in the global scope

That should be *caller* scope...
OK, you want to argue with everyone who supports the idea of macros. Fine.

Woah, easy there tiger! Did I at any point say, or even imply, that
macros were a bad idea? No.

All I've done so far is correct your claim that one couldn't do the
getValueWithDefault thing without a macro.


And as I've said before - you can't do it without multiple different functions.
I'm a C/C++ programmer at heart, I use macros there, and I know the
benefits (and otherwise) of them.


They why do you spend so much effort arguing AGAINST macros?
Let's see you to this as easily and as cleanly without macros:

define('FOREACH(X, K, V)', 'if (isset(X) && isarray(X)) foreach(X as K=>V)
FOREACH($var,$key,$value) {

// Process data in $key=>$value here.
}

FOREACH($var2, $key2, $value2) {
// Different processing of $key2=>value2 here
}

Again, that just implies bad practice. You should always know whether
a *variable* exists, and as such, should have no reason to call isset()
on it.


Not necessarily. It could be a list of checkboxes in your $_POST array, for
instance. It could be something in the $_SESSION array which may or may not
have been set.

Contrary to your belief, it is ALWAYS better to validate the existence of such
variables.

--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attglobal.net
==================
Apr 9 '06 #33
Oli Filth wrote:
Jerry Stuckle wrote:
Oli Filth wrote:
Jerry Stuckle said the following on 09/04/2006 06:14:
Oli Filth wrote:
>I have error level set to E_ALL | E_STRICT. The following code
>executes fine:
> <?php
>
> function getValueWithDefault(&$array, $key, $default = NULL)
> {
> return (isset($array[$key])) ? $array[$key] : $default;
> }
>
> $var = array();
> echo getValueWithDefault($var, "Roger", "Dodger") . "\n";
>
> ?>
>
>I see no reason why an error/warning should get thrown. isset()
>simply looks for an element with the specified key name in the
>associative array. In an empty array, the key doesn't exist, so
>isset() returns false.
>

That's not what I said. I said if $var is EMPTY.
From the PHP manual for empty():

"The following things are considered to be empty:
...
array() (an empty array)
..."

Yes, the array is empty. But $var is not! It contains an empty array.

No, $var doesn't *contain* an empty array, $var *is* an empty array.


That's YOUR definition.

Most of us understand there is a difference between an empty array and an empty
variable.

$var = null is an empty variable.
$var = array() contains an empty array.

<?php
$var = array();
echo empty($var) ? "TRUE" : "FALSE"; // echoes "TRUE"
?>

Take out the $var=array() line and see what you get.

So you mean "undefined"? Going back to the original purpose of this
function/macro, why would you ever want to call it on an undefined array?

Because it may or may not exist, that's why.

I thought the purpose was to check for the existence of an *entry* in
an associative array, such as $_POST, etc.


Yes, and first you have to ensure the array itself exists.
On the other hand, checking for the existence of a *variable* implies
bad practice. There should be no need. You should always know a
priori what variables exist at any given point in your code (assuming
the wonders of register_globals are disabled).

You really don't understand PHP, do you?

Checking for the existence of a *variable* is required for good programming
practice in PHP. You never know what may have been passed in a GET or POST
operation, for instance. And you don't necessarily know what may have been
saved in a cookie or the session.

Checking to see if these exist is very important in PHP programming!

But anyway, removing the $var = array() line does not result in any
error/warning. Because it's being passed by reference, PHP
automatically creates a variable $var in the global scope (because for
all it knows, this could be an output argument for the function).


Yep, and now you have changed the variable, haven't you?

Only if it was undefined in the first place, which would be bad
practice.


No, it could be perfectly normal. What if the variable you're trying to check
is $_POST['cblist'], which itself may be an array of checkbox values?

If no checkboxes are checked, the array doesn't even exist in $_POST.
--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attglobal.net
==================
Apr 9 '06 #34
Jerry Stuckle wrote:
Kimmo Laine wrote:
"Emil" <em**************@podczta.onet.pl> wrote in message
Is there any hope that new versions of PHP
will support macros similar to C or C++?
I've searched manual and didn't find anything
except define directive, but it can be used
to define constant values only.
Of course it is not THAT neccessary functionality,
but it could be very useful.


What's the actual difference between a function and a macro? How would use
of macros differ from functions?


Personally, one construct I use heavily and would like to replace with a macro:

$var = isset($_POST['postvar']) ? $_POST['postvar'] . 'default value';


It's unfortunate that the javascript approach does not work (since in
php a boolean is returned):
$var = $_POST['postvar'] . 'default value';

Macros are not necessarily more efficient. Depends on the context.
For example, if I had a large (global) object or array (or string) that
I wanted to keep referring to, but I didn't feel like passing it around
nor declaring it globally, a macro might be well suited to contain the
definition. But it would not be as efficient as toting around a
pointer to it. But regardless of these examples one way or another, it
is very rare for these types of efficiency differences to matter,
unless you are well buried in nested loops. As Dana Cartwright pointed
out, it is usually more a matter of mindset and convenience.

There is an approach (that I use in another context) that I think one
could use that would support macros, but it's not clean, and it would
take very careful programming... If you have an auto_prepend_file, you
can determine, within the auto_prepend_file, that it is an
auto_prepend_file and also the main file name (via
get_included_files()). In this case, you could use file_get_contents
on the upcoming, but to then unread/unparsed, file to slurp it in and
effect any macro substitutions, and then replace the original file.
This scheme can work, but it has a few major issues that must be
accounted for.
1. The scheme as outlined, leaves a changed file. Thus, the first
thing the revised file must do is to replace itself with the original
file (and don't forget to use the same time/date info).
2. How do you deal with a file that has parse errors? In that case,
the code injected at the beginning of the file would never be run.
Better account for this. And by the way, remember that the injected
code should all be on one line, so that the line numbers of any errors
are reported correctly.
3. Do you really want to write a parser? I'd rather not. But now one
must be aware that macro definitions within strings will also be
expanded.

Csaba Gabor from Vienna

Apr 9 '06 #35
Jerry Stuckle wrote:
Tim Martin wrote:
Used judiciously these sorts of techniques can open up all sorts of
possibilities (I've seen generic type containers implemented in pure C
using macros), but the general consensus is that the potential for
misuse is far too great and modern language constructs have obviated
all the genuine needs for such techniques.

What "General consensus"? I haven't heard that.


For example, Sutter / Alexandrescu, "C++ Coding standards". They dismiss
macros in no uncertain terms. You could argue about quite how widely
accepted this viewpoint is (not that I have any interest in such an
argument).

I deliberately phrased it like that to avoid giving the impression that
I endorse this consensus myself. Personally, I think there are plenty of
valid uses for macros in C (provided they are used with care). Whether
the benefits outweigh the costs in PHP (or indeed C++) is much less obvious.
And just because someone might misuse them means no one can have them?
People might misuse functions - get rid of them. Someone might misuse
relational databases - get rid of them.

It's not a valid argument.


That wouldn't be a valid argument, but that wasn't the extent of my
argument. You have to weigh up the potential benefits against costs. The
fact that inexperienced programmers might end up using them to create
unmaintainable code is a very definite cost. So far I haven't seen any
real benefits.

Out of interest, do you think that register_globals should be enabled by
default, since it causes no problems for people who write correct code?
To the OP: What are you trying to achieve with macros? With a
combination of pass-by-reference, soft references and eval() you can
achieve many of the things that C macros are able to achieve, with
better syntax and less potential for misuse.


Make code clearer, more concise and more maintainable. All of which can
be increased by the judicious use of macros.


The question is whether the same thing can be achieved by judicious use
of existing constructs, without having to introduce macros into the
language. So far, I haven't seen any proof otherwise.

Tim
Apr 9 '06 #36
Chung Leong wrote:
Tim Martin wrote:
Used judiciously these sorts of techniques can open up all sorts of
possibilities (I've seen generic type containers implemented in pure C
using macros), but the general consensus is that the potential for
misuse is far too great and modern language constructs have obviated all
the genuine needs for such techniques.


Personally I really dislike this brief in the CS circle that somehow
programmers need to be saved from themselves. It arises from the same
elitist, I-know-what's-best-for-you mentality prevalent in academia.
More than just a tool, these ivory tower geeks want a computer language
to enforce their values and way of thinking.


I have a fair amount of scepticism for this way of thinking myself. But
at the same time, I think anyone who's developed software in a team
environment will understand that at least one requirement of good code
is that it be readable by other people. Constraining programming style
(whether it be with language features, formal coding standards or
informal unspoken agreement) is to some extent a necessary part of that.

The CS formalism that tries to save programmers from themselves may be
too far in one direction, but I think regarding the programmer as king
who should have all their wishes fulfilled is too far in the other.

Tim
Apr 9 '06 #37
Jerry Stuckle wrote:
Oli Filth wrote:
Jerry Stuckle wrote:
Oli Filth wrote:
Jerry Stuckle said the following on 09/04/2006 06:14:
>That's not what I said. I said if $var is EMPTY.

From the PHP manual for empty():

"The following things are considered to be empty:
...
array() (an empty array)
..."

Yes, the array is empty. But $var is not! It contains an empty array.
No, $var doesn't *contain* an empty array, $var *is* an empty array.


That's YOUR definition.

Most of us understand there is a difference between an empty array and an empty
variable.

$var = null is an empty variable.
$var = array() contains an empty array.


Disregarding whether or not we think that *contains* or *is* is the
appropriate word here, nevertheless both of these examples evaluate to
empty in PHP - which I think is the only appropriate criterion for
whether we can consider something "empty".

[IMO, I would define the first one as "a null variable", and the second
one as "a variable that is an empty array". In PHP, "empty" is not a
definition of a variable; it doesn't uniquely tell you what state that
variable is in.]

The term "empty" is, at best, vacuous. $var = 0, $var = NULL, $var =
array() and undefined variables all evaluate to "empty". How can
something that doesn't even exist have measurable state?!

I'm fully aware that the two examples you gave are not identically
equal; they have different types. Nevertheless, with an empty array
(which fulfils the PHP definition of an empty variable), the code I
posted way back works correctly.

Not to mention that even if you do set $var = null, then it still works
correctly, without errors or warnings, and does not alter the original
variable.

I thought the purpose was to check for the existence of an *entry* in
an associative array, such as $_POST, etc.


Yes, and first you have to ensure the array itself exists.


See below...

On the other hand, checking for the existence of a *variable* implies
bad practice. There should be no need. You should always know a
priori what variables exist at any given point in your code (assuming
the wonders of register_globals are disabled).


You really don't understand PHP, do you?


I'll choose to ignore that question....

Checking for the existence of a *variable* is required for good programming
practice in PHP. You never know what may have been passed in a GET or POST
operation, for instance. And you don't necessarily know what may have been
saved in a cookie or the session.
Checking to see if these exist is very important in PHP programming!


I'm perfectly aware of that. Validation/checking for existence of
$_POST, etc, members is of course good practice. But you don't have to
check for the existence of $_POST itself.

Yep, and now you have changed the variable, haven't you?


Only if it was undefined in the first place, which would be bad
practice.


No, it could be perfectly normal. What if the variable you're trying to check
is $_POST['cblist'], which itself may be an array of checkbox values?

If no checkboxes are checked, the array doesn't even exist in $_POST.


This is one situation I admit I had not thought of. You could validly
use this as an argument for use of a macro here, although IMHO it's a
very limited case, compared to the set of cases which the functional
version deals with fine.

[My technical get-out clause is that the HTML syntax which results in a
sub-array within $_GET/$_POST is actually invalid, and so we can ignore
this case too!]
--
Oli

Apr 9 '06 #38
On 09/04/2006 16:51, Oli Filth wrote:

[snip]
[My technical get-out clause is that the HTML syntax which results in
a sub-array within $_GET/$_POST is actually invalid, and so we can
ignore this case too!]


<input name="control-name[]" ...>

?

There's nothing remotely invalid about that, provided the browser
encodes the brackets for submission when necessary (they aren't
permitted within query strings, for example).

Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Apr 9 '06 #39
Michael Winter wrote:
On 09/04/2006 16:51, Oli Filth wrote:

[snip]
[My technical get-out clause is that the HTML syntax which results in
a sub-array within $_GET/$_POST is actually invalid, and so we can
ignore this case too!]


<input name="control-name[]" ...>

?

There's nothing remotely invalid about that


Hmmm, you're absolutely correct! I could have sworn that once upon a
time I read that use of brackets in element names was invalid HTML, and
I found it to be the case running against the validator. But checking
against the W3C validator now, that doesn't seem to be the case.

I stand corrected. :)

--
Oli

Apr 9 '06 #40

Oli Filth wrote:
function getWithDefault(&$array, $key, $default = NULL)
{
return (isset($array[$key])) ? $array[$key] : $default;
}

Clever. Very clever.

Apr 9 '06 #41
On 09/04/2006 17:50, Oli Filth wrote:
Michael Winter wrote:


[snip]
<input name="control-name[]" ...>

?

There's nothing remotely invalid about that


Hmmm, you're absolutely correct! I could have sworn that once upon a
time I read that use of brackets in element names was invalid HTML,
and I found it to be the case running against the validator.


Perhaps you duplicated the value in an id attribute? The ID type is very
restrictive (letters, numbers, periods, colons, hyphens, and underscores).

Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Apr 9 '06 #42
Tim Martin wrote:
I have a fair amount of scepticism for this way of thinking myself. But
at the same time, I think anyone who's developed software in a team
environment will understand that at least one requirement of good code
is that it be readable by other people. Constraining programming style
(whether it be with language features, formal coding standards or
informal unspoken agreement) is to some extent a necessary part of that.


I agree with that up to a point. Readability obviously aids
development. On the other hand it has come to be that some people see
it as an end in itself. With aesthetic factor as the chief motive, they
busy themselves hiding "messy" parts of their code behind layers of
abstractions. This actually ends up decreasing readability since you
can't read what you can't see.

Looking at the issue empirically, I don't see macros as troublesome.
The source codes of such major projects as Linux, Apache, and PHP
itself are littered through out with macros. Since programmer usually
use them for oft-repeated code segments, you get accustomed to the
macros after a while, even though they look highly opaque at a glance.
In my opinion C++ templates are far less readable.

Apr 9 '06 #43
Tim Martin wrote:
Jerry Stuckle wrote:
Tim Martin wrote:
Used judiciously these sorts of techniques can open up all sorts of
possibilities (I've seen generic type containers implemented in pure
C using macros), but the general consensus is that the potential for
misuse is far too great and modern language constructs have obviated
all the genuine needs for such techniques.

What "General consensus"? I haven't heard that.

For example, Sutter / Alexandrescu, "C++ Coding standards". They dismiss
macros in no uncertain terms. You could argue about quite how widely
accepted this viewpoint is (not that I have any interest in such an
argument).


That's hardly a "general consensus". It's also about C/C++, not PHP.

And it goes against virtually every "coding standard" I've ever seen in C/C++.

I deliberately phrased it like that to avoid giving the impression that
I endorse this consensus myself. Personally, I think there are plenty of
valid uses for macros in C (provided they are used with care). Whether
the benefits outweigh the costs in PHP (or indeed C++) is much less
obvious.
And just because someone might misuse them means no one can have
them? People might misuse functions - get rid of them. Someone might
misuse relational databases - get rid of them.
>

It's not a valid argument.

That wouldn't be a valid argument, but that wasn't the extent of my
argument. You have to weigh up the potential benefits against costs. The
fact that inexperienced programmers might end up using them to create
unmaintainable code is a very definite cost. So far I haven't seen any
real benefits.


The potential benefits of having them are that they can make coding more
understandable and easier to maintain.

The lack of macros doesn't give you the option.

Out of interest, do you think that register_globals should be enabled by
default, since it causes no problems for people who write correct code?


An entirely different discussion - which I am not going to get into here.
To the OP: What are you trying to achieve with macros? With a
combination of pass-by-reference, soft references and eval() you can
achieve many of the things that C macros are able to achieve, with
better syntax and less potential for misuse.

Make code clearer, more concise and more maintainable. All of which
can be increased by the judicious use of macros.

The question is whether the same thing can be achieved by judicious use
of existing constructs, without having to introduce macros into the
language. So far, I haven't seen any proof otherwise.

Tim


No it can't. Read my other posts.

--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attglobal.net
==================
Apr 9 '06 #44
Chung Leong wrote:
Tim Martin wrote:

In my opinion C++ templates are far less readable.


Amen! Even though I am a heavy user of C++ templates and do my best to make
them clearer.
--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attglobal.net
==================
Apr 9 '06 #45
Csaba Gabor wrote:
3. Do you really want to write a parser? I'd rather not. But now one
must be aware that macro definitions within strings will also be
expanded.


One does not need to write full-blown parser to protect strings and
other lexical elements where partial tokeniser will do the job just fine.

Roman
Apr 10 '06 #46
Jerry Stuckle wrote:
Tim Martin wrote:
Jerry Stuckle wrote:
Tim Martin wrote:

Used judiciously these sorts of techniques can open up all sorts of
possibilities (I've seen generic type containers implemented in pure
C using macros), but the general consensus is that the potential for
misuse is far too great and modern language constructs have obviated
all the genuine needs for such techniques.
What "General consensus"? I haven't heard that.
For example, Sutter / Alexandrescu, "C++ Coding standards". They
dismiss macros in no uncertain terms. You could argue about quite how
widely accepted this viewpoint is (not that I have any interest in
such an argument).


That's hardly a "general consensus".


I quoted that as one example. As I say, I don't have any particular
interest in arguing over how widely shared this opinion is. I'll gladly
modify my original statement to "some people believe that..." if it
makes you happier.
It's also about C/C++, not PHP.
My original comment was about usage of macros in languages that have
them (i.e. C and C++), so this is an appropriate example. I'm obviously
not going to find any coding standards that forbid using macros in PHP.

For what it's worth, I've spent a lot of time writing C and I've used
macros extensively. When used properly I believe they can make code much
easier to maintain. However, I haven't found the same need in PHP.
The potential benefits of having them are that they can make coding more
understandable and easier to maintain.


So you say. I'm yet to see any real examples of situations in PHP where
macros give a significant benefit and similar behaviour couldn't be
achieved either by using an existing language construct, or by making a
small but less significant change to the language.

Tim
Apr 10 '06 #47
Tim Martin wrote:
Jerry Stuckle wrote:
Tim Martin wrote:
Jerry Stuckle wrote:

Tim Martin wrote:

> Used judiciously these sorts of techniques can open up all sorts of
> possibilities (I've seen generic type containers implemented in
> pure C using macros), but the general consensus is that the
> potential for misuse is far too great and modern language
> constructs have obviated all the genuine needs for such techniques.
>

What "General consensus"? I haven't heard that.
For example, Sutter / Alexandrescu, "C++ Coding standards". They
dismiss macros in no uncertain terms. You could argue about quite how
widely accepted this viewpoint is (not that I have any interest in
such an argument).

That's hardly a "general consensus".

I quoted that as one example. As I say, I don't have any particular
interest in arguing over how widely shared this opinion is. I'll gladly
modify my original statement to "some people believe that..." if it
makes you happier.
It's also about C/C++, not PHP.

My original comment was about usage of macros in languages that have
them (i.e. C and C++), so this is an appropriate example. I'm obviously
not going to find any coding standards that forbid using macros in PHP.

For what it's worth, I've spent a lot of time writing C and I've used
macros extensively. When used properly I believe they can make code much
easier to maintain. However, I haven't found the same need in PHP.
The potential benefits of having them are that they can make coding
more understandable and easier to maintain.

So you say. I'm yet to see any real examples of situations in PHP where
macros give a significant benefit and similar behaviour couldn't be
achieved either by using an existing language construct, or by making a
small but less significant change to the language.

Tim


Again - read back through other posts in this thread.

--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attglobal.net
==================
Apr 10 '06 #48

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

21
by: Chris Reedy | last post by:
For everyone - Apologies for the length of this message. If you don't want to look at the long example, you can skip to the end of the message. And for the Python gurus among you, if you can...
699
by: mike420 | last post by:
I think everyone who used Python will agree that its syntax is the best thing going for it. It is very readable and easy for everyone to learn. But, Python does not a have very good macro...
16
by: mike420 | last post by:
Tayss wrote: > > app = wxPySimpleApp() > frame = MainWindow(None, -1, "A window") > frame.Show(True) > app.MainLoop() > Why do you need a macro for that? Why don't you just write
37
by: michele.simionato | last post by:
Paul Rubin wrote: > How about macros? Some pretty horrible things have been done in C > programs with the C preprocessor. But there's a movememnt afloat to > add hygienic macros to Python. Got any...
8
by: Michael Winter | last post by:
In a recent post ("About C error" by Victor, 21 Sep 2003), comments were made about the poster's use of macros. What I would like to know is why they are considered bad? I'm not referring to...
11
by: Ben Hetland | last post by:
....in certain cituations they can be useful if not for anything else, then at least for saving a lot of repetetetetetitititive typing. :-) Beyond the point of "do something better instead", I'm...
3
by: Stephen Sprunk | last post by:
On a project I'm working on, I ran across the following macros: /* assume s is struct stream *, s->p is char, v is unit16_t or uint32_t */ #define in_uint16_le(s,v) { v = *((s)->p++); v +=...
11
by: San | last post by:
hi there, I am new to c++ and tryig to learn the basics of the c++ concepts. While I was reading the templates, I realize that the templates are a syntax that the compilar expands pased upon the...
33
by: Robert Seacord | last post by:
When writing C99 code is a reasonable recommendation to use inline functions instead of macros? What sort of things is it still reasonable to do using macros? For example, is it reasonable to...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.