473,854 Members | 1,528 Online
Bytes | Software Development & Data Engineering Community
+ 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
47 32937
>> 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_wi th_default($nam e, $default = 'default value')
{
if (isset($_POST[$name]))
{
return $_POST[$name];
}
else
{
return $default;
}
}

then later

$var = get_post_var_wi th_default('pos tvar');

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_wi th_default($nam e, $default = 'default value')
{
if (isset($_POST[$name]))
{
return $_POST[$name];
}
else
{
return $default;
}
}

then later

$var = get_post_var_wi th_default('pos tvar');

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_DEFAUL T($_POST['myvar']), 'default value');
$var2 = GET_WITH_DEFAUL T_VALUE($myarra y['test'], 'default_value) ;
--
=============== ===
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attgl obal.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*******@attgl obal.net
=============== ===
Apr 8 '06 #16
Jerry Stuckle said the following on 08/04/2006 16:11:
Tim Martin wrote:

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

then later

$var = get_post_var_wi th_default('pos tvar');

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_DEFAUL T($_POST['myvar']), 'default value');
$var2 = GET_WITH_DEFAUL T_VALUE($myarra y['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(pa th,macros)
{
text = get_file_conten t(path);

// expand'em - skipped

put_file_conten t(path.'.expand ed',
'define(\'EXPAN DED\', 1);\n\n' . text);
}

@include __FILE__.'.expa nded"

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(pa th,macros)
{
text = get_file_conten t(path);

// expand'em - skipped

put_file_conten t(path.'.expand ed',
'define(\'EXPAN DED\', 1);\n\n' . text);
}

@include __FILE__.'.expa nded"

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__.'.expa nded';

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

function ExpandMacros($p ath)
{
$text = file_get_conten ts($path);

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

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

file_put_conten ts($path.'.expa nded', $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
substitutio ns 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(pa th,macros)
{
text = get_file_conten t(path);

// expand'em - skipped

put_file_conten t(path.'.expand ed',
'define(\'EXPAN DED\', 1);\n\n' . text);
}

@include __FILE__.'.expa nded"

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

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

Similar topics

21
3001
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 spare the time, I would appreciate any comments (including words like evil and disgusting, if you think they are applicable :-}) on the example here. Kenny -
699
34378
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 capabilities, unfortunately. I'd like to know if it may be possible to add a powerful macro system to Python, while keeping its amazing syntax, and if it could be possible to add Pythonistic syntax to Lisp or Scheme, while keeping all of the...
16
2432
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
2824
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 thoughts about that? "Movement" seems quite an exaggeration. Maybe 2-3 people made some experiments, but nobody within the core Python developers seems to be willing to advocate the introduction of macros. > Why should you care whether the...
8
7243
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 their use as 'functions'; I realise the loss of type-safety and the possible evaluation errors that can occur. However, what would be the harm with numeric and text literals? Consider a number that plays a significant role in the implementation of...
11
2871
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 curious about how the following syntactical problem can be solved. It should apply equally to C and C++ as it mainly is a preprocessor-related problem. I tryed to define something similar to the following example: ...
3
2671
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 += *((s)->p++) << 8; } #define in_uint32_le(s,v) { in_uint16_le(s,v) \ v += *((s)->p++) << 16; v += *((s)->p++) << 24; } I'm personally not fond of function-like macros and wanted to turn these into static inline functions, but I'm having trouble doing...
11
22392
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 type specified. This is much similar like a macro expansion in C. can anyone please explain advantages of one over the other ? Thanks in advance -
33
8916
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 write type generic functions macros? #define CUBE(I) ( (I) * (I) * (I) ) Is there some more concise set of things where inline functions should be used instead of macros? Multi-statement macros, for example?
0
11031
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10685
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10763
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10371
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7082
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5942
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4563
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 we have to send another system
2
4162
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3188
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.