|
Posted by Roman Ziak on 11/18/41 11:44
Tim Martin wrote:
> Kimmo Laine wrote:
>> "Emil" <emjot_wytnij_to_@podczta.onet.pl> wrote in message
>> news:e15ag1$3ee$1@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
Navigation:
[Reply to this message]
|