473,839 Members | 1,540 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 32931
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 getValueWithDef ault(&$array, $key, $default = NULL)
{
return (isset($array[$key])) ? $array[$key] : $default;
}

$var = array();
echo getValueWithDef ault($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,$k ey,$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*******@attgl obal.net
=============== ===
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 getValueWithDef ault(&$array, $key, $default = NULL)
> {
> return (isset($array[$key])) ? $array[$key] : $default;
> }
>
> $var = array();
> echo getValueWithDef ault($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
getValueWithDef ault 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,$k ey,$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 getValueWithDef ault(&$array, $key, $default = NULL)
>> {
>> return (isset($array[$key])) ? $array[$key] : $default;
>> }
>>
>> $var = array();
>> echo getValueWithDef ault($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
automatical ly 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
getValueWithDef ault 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,$k ey,$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*******@attgl obal.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 getValueWithDef ault(&$array, $key, $default = NULL)
> {
> return (isset($array[$key])) ? $array[$key] : $default;
> }
>
> $var = array();
> echo getValueWithDef ault($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
>associativ e 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_global s 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
automaticall y 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*******@attgl obal.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_fi le, you
can determine, within the auto_prepend_fi le, that it is an
auto_prepend_fi le and also the main file name (via
get_included_fi les()). In this case, you could use file_get_conten ts
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_global s 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_global s 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

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

Similar topics

21
3000
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
34361
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
2430
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
2822
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
7242
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
2867
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
2670
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
22388
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
8915
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
9697
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10906
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
10585
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
10647
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
10292
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...
1
7828
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7017
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();...
1
4482
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
3
3132
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.