# proposed access modifier "silent" ... was: Re:  Implicit isset/isempty check on short-ternary operator

- Thread: https://externals.io/message/51857
- Original archive: https://news-web.php.net/php.internals/51857
- Started by D. Dante Lorenso on 2011-04-11T02:22:58+00:00
- Messages: 23
- Reply by email to internals@lists.php.net
- More for agents: search with https://externals.io/search.md?q={query} · JSON API at https://externals.io/api · documentation at https://externals.io/llms.txt

---

## #51857 — D. Dante Lorenso — 2011-04-11T02:22:58+00:00

URL: https://externals.io/message/51857#51857

The problem with implementing "ifsetor", "filled", or "??" in userland 
is that the "not set" or "undefined" warning is fired before the 
variable is passed to the underlying function/method.

Is it possible to add a modifier that turns off warnings for undefined 
variables whenever that specific method is called?  Something like:

class Utility {
   public silent function `filled()` {
     $args = `func_get_args()`;
     foreach ($args as $arg) {
       if (!empty($arg)) { return $arg; }
     }
     return false;
   }
}

$x = Utility::filled($my_undef, $x['undef'], $nosuch, 'default');

The modifier "silent" will turn all undefined or "not isset()" variables 
into `NULL` values when being passed to the method and no warnings will be 
issued.

Then, we can build our own damn functions as we see fit without the fuss.

-- Dante

---

## #51858 — Matt Wilson — 2011-04-11T02:35:04+00:00

URL: https://externals.io/message/51857#51858 · In reply to: #51857

@.



> The problem with implementing "ifsetor", "filled", or "??" in userland is that the "not set" or "undefined" warning is fired before the variable is passed to the underlying function/method.
> 
> Is it possible to add a modifier that turns off warnings for undefined variables whenever that specific method is called?  Something like:
> 
> class Utility {
>  public silent function `filled()` {
>    $args = `func_get_args()`;
>    foreach ($args as $arg) {
>      if (!empty($arg)) { return $arg; }
>    }
>    return false;
>  }
> }
> 
> $x = Utility::filled($my_undef, $x['undef'], $nosuch, 'default');
> 
> The modifier "silent" will turn all undefined or "not isset()" variables into `NULL` values when being passed to the method and no warnings will be issued.
> 
> Then, we can build our own damn functions as we see fit without the fuss.
> 
> -- Dante

---

## #51859 — Stas Malyshev — 2011-04-11T02:47:13+00:00

URL: https://externals.io/message/51857#51859 · In reply to: #51858

Hi!

> @.

Note however it does not exactly "turn off" the warning, only changes it 
to not reported. It's still generated and can be picked up by handlers, 
for example.
-- 
Stanislav Malyshev, Software Architect
SugarCRM: http://www.sugarcrm.com/
(408)454-6900 ext. 227

---

## #51860 — Hannes Landeholm — 2011-04-11T08:10:57+00:00

URL: https://externals.io/message/51857#51860 · In reply to: #51859

@ is not convenient since it turns off error reporting for all errors. I
don't know how many times I've silenced a notice and got a blank page in my
face as a "thank you for accidentally silencing that fatal error too".

"Silent" is reserved for the purpose of the silence operator though @ so
using that as a keyword for something else would be confusing.


It just struck me that the ~real~ problem is that sometimes you want array
access that should define undefined indexes as being null (a good
placeholder for this purpose). How about (instead of the previously proposed
?? and isnotempty and whatnot) simply changing the "array access syntax" to
simply allow an optional "?" operator at the end signaling that the
condition where the index isn't defined isn't unexpected?

For example:

$value = isset($arr["foo"])? $arr["foo"]: null;
$value = isset($arr[$foo])? $arr[$foo]: null;

would be replaced with: (respectively)

$value = $arr["foo"?];
$value = $arr[$foo?];

it would also worked chained:

$value = $arr["foo"?]["bar"]["baz"?]

(if [foo] doesn't exist value will be null.. if [foo] exists [foo][bar] is
expected to exist but [foo][bar][baz] may or may not exist... if not, value
will once again be null)

This way it would only apply to array access which was a +1 for some.

This could also be extended too replace null with something different (by
allowing an expression after the "?" like "null" or "foo" . "bar") but I
think careful use-case research should be done to determine if it's really
needed first...

I realize this partially collides with the use of ? so it would be more
difficult to implement but it's far from impossible.. it just requires a
little ahead-parsing in brackets [] to know if the "?" is a ternary if or if
it's a "not exists is not undefined" operator (is the : missing or not?).
Otherwise "??" could simply be used instead or a completely different
operator...

~Hannes



> Hi!
>
>  @.
> > […]
>
> Note however it does not exactly "turn off" the warning, only changes it to
> not reported. It's still generated and can be picked up by handlers, for
> example.
> --
> Stanislav Malyshev, Software Architect
> SugarCRM: http://www.sugarcrm.com/
> (408)454-6900 ext. 227

---

## #51861 — Ben Schmidt — 2011-04-11T12:20:12+00:00

URL: https://externals.io/message/51857#51861 · In reply to: #51860

I think another problem with using @ is that it is done by the caller,
not the callee, so it doesn't allow functions like issetor() to be
implemented in userland without expecting every caller to do pass the
variable while silencing errors.

I also don't think the inconvenience is restricted to arrays. I
frequently use the idiom isset(X)?X:Y with X simply being a variable.
It's not just about silencing a notice, but about providing an
alternative/default value.

If doing the suppression of undefined notices be better if the ? was put after the 
opening square bracket, thereby removing the ambiguity (which I think would be 
more troublesome than you think)? $array[?"foo"]

Ben.




> @ is not convenient since it turns off error reporting for all errors. I
> don't know how many times I've silenced a notice and got a blank page in my
> face as a "thank you for accidentally silencing that fatal error too".
>
> "Silent" is reserved for the purpose of the silence operator though @ so
> using that as a keyword for something else would be confusing.
>
>
> It just struck me that the ~real~ problem is that sometimes you want array
> access that should define undefined indexes as being null (a good
> placeholder for this purpose). How about (instead of the previously proposed
> ?? and isnotempty and whatnot) simply changing the "array access syntax" to
> simply allow an optional "?" operator at the end signaling that the
> condition where the index isn't defined isn't unexpected?
>
> For example:
>
> $value = isset($arr["foo"])? $arr["foo"]: null;
> $value = isset($arr[$foo])? $arr[$foo]: null;
>
> would be replaced with: (respectively)
>
> $value = $arr["foo"?];
> $value = $arr[$foo?];
>
> it would also worked chained:
>
> $value = $arr["foo"?]["bar"]["baz"?]
>
> (if [foo] doesn't exist value will be null.. if [foo] exists [foo][bar] is
> expected to exist but [foo][bar][baz] may or may not exist... if not, value
> will once again be null)
>
> This way it would only apply to array access which was a +1 for some.
>
> This could also be extended too replace null with something different (by
> allowing an expression after the "?" like "null" or "foo" . "bar") but I
> think careful use-case research should be done to determine if it's really
> needed first...
>
> I realize this partially collides with the use of ? so it would be more
> difficult to implement but it's far from impossible.. it just requires a
> little ahead-parsing in brackets [] to know if the "?" is a ternary if or if
> it's a "not exists is not undefined" operator (is the : missing or not?).
> Otherwise "??" could simply be used instead or a completely different
> operator...
>
> ~Hannes
>
> 
>
> > […]

---

## #51862 — Ben Schmidt — 2011-04-11T12:52:09+00:00

URL: https://externals.io/message/51857#51862 · In reply to: #51861

> If doing the suppression of undefined notices be better if the ? was put after the
> opening square bracket, thereby removing the ambiguity (which I think would be
> more troublesome than you think)? $array[?"foo"]

I suppose a non-array-specific version would be to put it after the $.

$?variable
$?array['foo']['bar']

I wonder if you could even use : with this syntax.

$?variable:"default"
$?array['foo']['bar']:"default"

Perhaps using it in function definitions is something to consider, too,
for a callee-specified undefined-notice-silencing mechanism.

function foo($?arg) {
}

Doesn't work for the variable arguments case, though, without resorting
to something IMHO ugly/hard-to-read-and-understand like:

function foo(?) {
}

It's another idea to throw in the mix, though.

I do think the 'silent' modifier that was the original suggestion in
this thread is worth further thought. It may well allow userland
functions to be developed, which might be a benefit.

I personally, though, think a modified ternary operator like the
proposed ??: or the syntax above, is better.

Ben.

---

## #51863 — Etienne Kneuss — 2011-04-11T13:36:57+00:00

URL: https://externals.io/message/51857#51863 · In reply to: #51857

> The problem with implementing "ifsetor", "filled", or "??" in userland 
> is that the "not set" or "undefined" warning is fired before the 
> variable is passed to the underlying function/method.
> 
> Is it possible to add a modifier that turns off warnings for undefined 
> variables whenever that specific method is called?  Something like:

Short answer is no. See below.

> 
> class Utility {
>    public silent function `filled()` {
>      $args = `func_get_args()`;
>      foreach ($args as $arg) {
>        if (!empty($arg)) { return $arg; }
>      }
>      return false;
>    }
> }
> 
> $x = Utility::filled($my_undef, $x['undef'], $nosuch, 'default');
> 
> The modifier "silent" will turn all undefined or "not isset()" variables 
> into `NULL` values when being passed to the method and no warnings will be 
> issued.

This is not really possible without some major changes. You've to
understand that arguments are evaluated before the function/method call.
The notices are thus emited before even considering the function/method
call.

This is exactly why isset and empty are not functions, but language
constructs, so that they can work with variables in a special way.

> 
> Then, we can build our own damn functions as we see fit without the fuss.
> 
> -- Dante

---

## #51864 — Michael Morris — 2011-04-11T17:17:35+00:00

URL: https://externals.io/message/51857#51864 · In reply to: #51863

I might come off rather crumudgeonly here, but these last few threads I've
seen going across to
silence notices have a common theme - "I wanna be a lazier coder."

Which is fine - set the PHP error level to not show them.

But don't ask the engine to be rewritten to encourage bad coding practices
which failing to properly initialize variables is a prime example of.  It's
this sort of thinking that got register_globals and magic_quotes put into
the language no doubt. In the long run it's an extremely bad idea and needs
to be avoided.

-1

On Mon, Apr 11, 2011 at 9:36 AM, Etienne Kneuss <etienne@immomigsa.ch>wrote:

> 
> > […]
>
> Short answer is no. See below.
>
> > […]
>
> This is not really possible without some major changes. You've to
> understand that arguments are evaluated before the function/method call.
> The notices are thus emited before even considering the function/method
> call.
>
> This is exactly why isset and empty are not functions, but language
> constructs, so that they can work with variables in a special way.
>
> > […]

---

## #51865 — Pascal COURTOIS — 2011-04-11T17:50:05+00:00

URL: https://externals.io/message/51857#51865 · In reply to: #51864

Le 11/04/2011 19:17, Michael Morris a écrit :
> But don't ask the engine to be rewritten to encourage bad coding practices
> which failing to properly initialize variables is a prime example of.  It's
> this sort of thinking that got register_globals and magic_quotes put into
> the language no doubt. In the long run it's an extremely bad idea and needs
> to be avoided.

  +1

  Use APL if PHP is too verbose for you (good luck :-) )

---

## #51866 — Stas Malyshev — 2011-04-11T18:21:02+00:00

URL: https://externals.io/message/51857#51866 · In reply to: #51864

Hi!

> I might come off rather crumudgeonly here, but these last few threads I've
> seen going across to
> silence notices have a common theme - "I wanna be a lazier coder."

Laziness is a virtue for a coder :) At least, when it goes to avoid 
unnecessary work - in this example, boilerplate code.

> Which is fine - set the PHP error level to not show them.

This is not good enough - "not showed" errors are still generated and 
are quite expensive.

> But don't ask the engine to be rewritten to encourage bad coding practices
> which failing to properly initialize variables is a prime example of.  It's

The case we're dealing with is specifically about providing resolution 
for the case when the value is not initialized and the default value is 
provided. It is about making good code easier to write ("$foo[$bar] ?? 
$baz" instead of "isset($foo[$bar])?$foo[$bar]:$bar").
-- 
Stanislav Malyshev, Software Architect
SugarCRM: http://www.sugarcrm.com/
(408)454-6900 ext. 227

---

## #51867 — Matthew Weier O'Phinney — 2011-04-11T18:47:38+00:00

URL: https://externals.io/message/51857#51867 · In reply to: #51866

> > […]
>
> Laziness is a virtue for a coder :) At least, when it goes to avoid
> unnecessary work - in this example, boilerplate code.
>
> > […]
>
> This is not good enough - "not showed" errors are still generated and
> are quite expensive.
>
> > […]
>
> The case we're dealing with is specifically about providing resolution
> for the case when the value is not initialized and the default value
> is provided. It is about making good code easier to write ("$foo[$bar]
> ??  $baz" instead of "isset($foo[$bar])?$foo[$bar]:$bar").

+1

This is precisely the use case I originally (erroneously) thought the
ternary shortcut was for. It's not uncommon to use nested arrays or
objects for configuration -- and configuration is one place where you
may or may not have values. Having a shortcut to retrieve the value if
present or provide a default is not just laziness, but also a way to
improve your coding -- by removing yet another place for a typo. (Type
the array/object access ONCE instead of TWICE.)

-- 
Matthew Weier O'Phinney
Project Lead            | matthew@zend.com
Zend Framework          | http://framework.zend.com/
PGP key: http://framework.zend.com/zf-matthew-pgp-key.asc

---

## #51868 — Todd Ruth — 2011-04-11T19:08:15+00:00

URL: https://externals.io/message/51857#51868 · In reply to: #51866

I'm not arguing whether the following code fragment is good
or bad (it's certainly less than ideal), but given the recent 
threads, I thought I'd show how I feel I've been encourage by 
php to code:

<?php
$x = array();
$y = 'something';
$temp =& $x[$y];
$temp++;
unset($temp);
?>

I'm not sure where (if anywhere) that technique is documented
or even if it should be documented, but if you want to avoid
"Undefined index" notices, that's one of the more terse
approaches.  The relative brevity is more obvious when the
variable names are long and $temp is re-linked several times
before unsetting.  It's probably less clear than alternatives
unless you see it often.

Here is an application to the defaults for configurations thread:

<?php
$config = array();
$param = 'param1';
$temp =& $config[$param];
$temp = $temp ?: 'default';
unset($temp);
var_dump($config);
?>

It isn't beautiful, but it avoids writing "$config[$param]"
more than once and it avoids the notices.

- Todd

---

## #51869 — Matt Wilson — 2011-04-11T19:14:40+00:00

URL: https://externals.io/message/51857#51869 · In reply to: #51868

Something I've been doing for a long time is similar, but in my opinion a much better practice.

function coalesce(&$val, $ifnull = false)
{
	return empty($val) ? $ifnull : $val;
}

Add whatever restrictive logic you wish here, if empty() isn't good enough for your purposes. 

$_GET['mightnotexist'] = coalesce($_GET['mightnotexist'], 'default');

Personally, I think if you're writing your code where a variable's existence is ambiguous, you *should* be seeing notices.



> I'm not arguing whether the following code fragment is good
> or bad (it's certainly less than ideal), but given the recent 
> threads, I thought I'd show how I feel I've been encourage by 
> php to code:
> 
> <?php
> $x = array();
> $y = 'something';
> $temp =& $x[$y];
> $temp++;
> unset($temp);
> ?>
> 
> I'm not sure where (if anywhere) that technique is documented
> or even if it should be documented, but if you want to avoid
> "Undefined index" notices, that's one of the more terse
> approaches.  The relative brevity is more obvious when the
> variable names are long and $temp is re-linked several times
> before unsetting.  It's probably less clear than alternatives
> unless you see it often.
> 
> Here is an application to the defaults for configurations thread:
> 
> <?php
> $config = array();
> $param = 'param1';
> $temp =& $config[$param];
> $temp = $temp ?: 'default';
> unset($temp);
> var_dump($config);
> ?>
> 
> It isn't beautiful, but it avoids writing "$config[$param]"
> more than once and it avoids the notices.
> 
> - Todd

---

## #51870 — Etienne Kneuss — 2011-04-11T19:18:56+00:00

URL: https://externals.io/message/51857#51870 · In reply to: #51869

> Something I've been doing for a long time is similar, but in my opinion a much better practice.
> 
> function coalesce(&$val, $ifnull = false)
> {
> 	return empty($val) ? $ifnull : $val;
> }
> 
> Add whatever restrictive logic you wish here, if empty() isn't good enough for your purposes. 

The "problem" with such approach is that it will always end up defining
what $val is a reference of.

e.g.
$plop = coalesce($_GET['foo'], 'default']);

will end up leaving $_GET['foo'] assigned to null. That might be fine
with your usage, but having an operator for it would solve that
"problem".

Best,

> 
> $_GET['mightnotexist'] = coalesce($_GET['mightnotexist'], 'default');
> 
> Personally, I think if you're writing your code where a variable's existence is ambiguous, you *should* be seeing notices.
> 
> 
> 
> > […]

---

## #51871 — Etienne Kneuss — 2011-04-11T19:23:07+00:00

URL: https://externals.io/message/51857#51871 · In reply to: #51868

> I'm not arguing whether the following code fragment is good
> or bad (it's certainly less than ideal), but given the recent 
> threads, I thought I'd show how I feel I've been encourage by 
> php to code:
> 
> <?php
> $x = array();
> $y = 'something';
> $temp =& $x[$y];
> $temp++;
> unset($temp);
> ?>
> 
> I'm not sure where (if anywhere) that technique is documented
> or even if it should be documented, but if you want to avoid
> "Undefined index" notices, that's one of the more terse
> approaches.  The relative brevity is more obvious when the
> variable names are long and $temp is re-linked several times
> before unsetting.  It's probably less clear than alternatives
> unless you see it often.
> 
> Here is an application to the defaults for configurations thread:
> 
> <?php
> $config = array();
> $param = 'param1';
> $temp =& $config[$param];
> $temp = $temp ?: 'default';
> unset($temp);
> var_dump($config);
> ?>
> 
> It isn't beautiful, but it avoids writing "$config[$param]"
> more than once and it avoids the notices.

I believe that using + for configuration settings makes much more sense:

$defaults = array('foo' => 'bar', 'gee' => 'plop');
$conf += $defaults;

and that's it. You no longer have to worry about 'foo' or 'gee' being
defined, whether you use them or not: $conf is fully defined for every
possible configuration settings.

Now you could of course use the same mechanism for filling $_GET
and $_POST, but I usually prefer leaving $_GET and $_POST untouched, so
that it still reflects what the user actually sent, so even the
technique with references would not work for me.

Best,

> 
> - Todd

---

## #51872 — Chris Stockton — 2011-04-11T20:09:10+00:00

URL: https://externals.io/message/51857#51872 · In reply to: #51867

Hello,

On Mon, Apr 11, 2011 at 11:47 AM, Matthew Weier O'Phinney
<weierophinney@php.net> wrote:
> 
> > […]

My suggestion to use ?? I will say has little to do with laziness. I
would be happy with any solution that solves my problem, I just know
that implementing a patch for ?? would be simple enough (I could even
do so if requested). Everyone has different use patterns as shown in
other examples, this is natural and just comes with the domain.
However, you may find 415,000 reasons why this feature could be useful
for developers in [1].

I also really like the <whatevername>($foo['not exists'], $config['not
exists'], $foo, $bar, 'default') function. I personally only usually
need 1 default value but I feel like many people may find uses for
this as well.

In addition I would like to mention that the checking being "isset"
for such a feature would be a very reasonable option, seeing as empty
[2], array_key_exists [3] (7000 uses found only) etc type use cases
are probably going to be a big minority. Most of the time checks done
with empty() seem to be done on known or already isset() checked, I.E.
isset($foo['bar']) && !empty($foo['bar']) anyways.

Just some food for thought,

-Chris

[1] http://www.google.com/codesearch?hl=en&lr=&q=.*isset\%28.%2B%3F\%29[\s]{0%2C1}\%3F&sbtn=Search
[2] http://www.google.com/codesearch?hl=en&lr=&q=file%3A.*php+.*empty\%28.%2B%3F\%29[\s]{0%2C1}\%3F&sbtn=Search
[3] http://www.google.com/codesearch?hl=en&lr=&q=.*array_key_exists\%28.%2B%3F\%29[\s]{0%2C1}\%3F&sbtn=Search

---

## #51873 — Martin Scotta — 2011-04-11T23:30:46+00:00

URL: https://externals.io/message/51857#51873 · In reply to: #51872

It seems that there are no consensus about this feature so...

*if in doubt, leave it out.*


 Martin Scotta


On Mon, Apr 11, 2011 at 5:09 PM, Chris Stockton
<chrisstocktonaz@gmail.com>wrote:

> Hello,
>
> On Mon, Apr 11, 2011 at 11:47 AM, Matthew Weier O'Phinney
> <weierophinney@php.net> wrote:
> > […]
>
> My suggestion to use ?? I will say has little to do with laziness. I
> would be happy with any solution that solves my problem, I just know
> that implementing a patch for ?? would be simple enough (I could even
> do so if requested). Everyone has different use patterns as shown in
> other examples, this is natural and just comes with the domain.
> However, you may find 415,000 reasons why this feature could be useful
> for developers in [1].
>
> I also really like the <whatevername>($foo['not exists'], $config['not
> exists'], $foo, $bar, 'default') function. I personally only usually
> need 1 default value but I feel like many people may find uses for
> this as well.
>
> In addition I would like to mention that the checking being "isset"
> for such a feature would be a very reasonable option, seeing as empty
> [2], array_key_exists [3] (7000 uses found only) etc type use cases
> are probably going to be a big minority. Most of the time checks done
> with empty() seem to be done on known or already isset() checked, I.E.
> isset($foo['bar']) && !empty($foo['bar']) anyways.
>
> Just some food for thought,
>
> -Chris
>
> [1]
> http://www.google.com/codesearch?hl=en&lr=&q=.*isset\%28.%2B%3F\%29[\s]{0%2C1}\%3F&sbtn=Search<http://www.google.com/codesearch?hl=en&lr=&q=.*isset%5C%28.%2B%3F%5C%29[%5Cs]%7B0%2C1%7D%5C%3F&sbtn=Search>
> [2]
> http://www.google.com/codesearch?hl=en&lr=&q=file%3A.*php+.*empty\%28.%2B%3F\%29[\s]{0%2C1}\%3F&sbtn=Search<http://www.google.com/codesearch?hl=en&lr=&q=file%3A.*php+.*empty%5C%28.%2B%3F%5C%29[%5Cs]%7B0%2C1%7D%5C%3F&sbtn=Search>
> [3]
> http://www.google.com/codesearch?hl=en&lr=&q=.*array_key_exists\%28.%2B%3F\%29[\s]{0%2C1}\%3F&sbtn=Search<http://www.google.com/codesearch?hl=en&lr=&q=.*array_key_exists%5C%28.%2B%3F%5C%29[%5Cs]%7B0%2C1%7D%5C%3F&sbtn=Search

---

## #51874 — Stas Malyshev — 2011-04-12T09:04:36+00:00

URL: https://externals.io/message/51857#51874 · In reply to: #51873

Hi!

> It seems that there are no consensus about this feature so...
>
> *if in doubt, leave it out.*

I don't see any serious objections to it except comments from people 
that seem not really understand what this feature is about and complain 
about "bad code" which has nothing to do with the actual feature 
proposed. I am all for consensus, but I have very hard time accepting it 
as a valid objection, sorry.
-- 
Stanislav Malyshev, Software Architect
SugarCRM: http://www.sugarcrm.com/
(408)454-6900 ext. 227

---

## #51875 — Gustavo Lopes — 2011-04-12T09:21:58+00:00

URL: https://externals.io/message/51857#51875 · In reply to: #51874

Em Tue, 12 Apr 2011 10:04:36 +0100, Stas Malyshev <smalyshev@sugarcrm.com>  
escreveu:

> > […]
>
> I don't see any serious objections to it except comments from people  
> that seem not really understand what this feature is about and complain  
> about "bad code" which has nothing to do with the actual feature  
> proposed. I am all for consensus, but I have very hard time accepting it  
> as a valid objection, sorry.

I agree that argument is absurd... Even Freemarker, which is rather  
unforgiving with missing values (see  
http://freemarker.org/docs/app_faq.html#faq_picky_about_missing_vars ),  
provides this in the form unsafe_expr!default_expr. It's not about writing  
sloppy code, it's precisely the opposite -- identifying clearly and  
succinctly the regions where missing values are expected.

-- 
Gustavo Lopes

---

## #51876 — Mike Robinson — 2011-04-12T11:30:14+00:00

URL: https://externals.io/message/51857#51876 · In reply to: #51872

> My suggestion to use ?? I will say has little to do with laziness. I
> would be happy with any solution that solves my problem, I just know
> that implementing a patch for ?? would be simple enough (I could even
> do so if requested). Everyone has different use patterns as shown in
> other examples, this is natural and just comes with the domain.

Laziness should not be confused with a desire to write clean readable
code quickly. :)

I have use for this, it's a nice clean solution to a simple problem.

FWIW, +1.

Best Regards

Mike Robinson

---

## #51877 — Richard Quadling — 2011-04-12T11:33:17+00:00

URL: https://externals.io/message/51857#51877 · In reply to: #51857

Considering that the main impetus for these threads is to write code
that does not generate the notice regarding missing variables or
indices, neither isset() or empty() will provide that completely.

If a variable is declared, but assigned null, it is not set and it is
empty. But so what. The variable exists and will not generate a notice
if access is attempted. No suppression of the non existent notice is
necessary.

The issue is one of undefined variables and indices. That's what the
 `E_NOTICE` says ...

Notice: Undefined variable
Notice: Undefined index


To directly detect the presence of a key, then `array_key_exists()` is
the function that covers the requirement.

Global variables are easily detectable using array_key_exists($key, $GLOBALS);

Properties for an object ... `property_exists()`.

For locally scoped variables, the function `get_defined_vars()` can be
combined with `array_key_exists()`.

But the obvious overhead of having to extract all the variables into a
temp array is probably going to be a performance no-no.

The script below (and in [1] in case the formatting all goes wonky),
demonstrates this.

Ideally, a construct that specifically detects if a variable is
declared, irrespective of its value, would be the perfect solution as
this could be combined with isset() or empty() as the developer needs.

Richard.

[1] http://pastebin.com/qLNYtfAw

<?php
error_reporting(-1);

function report($desc, $isset, $empty, $defined) {
  return
    $desc .
    '  isset() = ' . ($isset   ? 'true ' : 'false') .
    '  empty() = ' . ($empty   ? 'true ' : 'false') .
    '  defined = ' . ($defined ? 'true ' : 'false') .
    PHP_EOL;
}

function tester() {
  // $undefined_variable = '';
  $defined_variable_null_value = null;
  $defined_variable_value = 'non null variable';
  $array = array(
   // 'undefined_key' => '',
   'defined_key_null_value' => null,
   'defined_key_value' => 'non null element',
  );

  $defined_vars = `get_defined_vars()`;

  echo
    report('Undefined variable              ',
      isset($undefined_variable),
      empty($undefined_variable),
      array_key_exists('undefined_variable', $defined_vars)),

    report('Defined variable null value     ',
      isset($defined_variable_null_value),
      empty($defined_variable_null_value),
      array_key_exists('defined_variable_null_value', $defined_vars)),

    report('Defined variable non-null value ',
      isset($defined_variable_value),
      empty($defined_variable_value),
      array_key_exists('defined_variable_value', $defined_vars)),

    report('Undefined key                   ',
      isset($array['undefined_key']),
      empty($array['undefined_key']),
      array_key_exists('undefined_key', $array)),

    report('Undefined key null value        ',
      isset($array['defined_key_null_value']),
      empty($array['defined_key_null_value']),
      array_key_exists('defined_key_null_value', $array)),

    report('Undefined key non-null value    ',
      isset($array['defined_key_value']),
      empty($array['defined_key_value']),
      array_key_exists('defined_key_value', $array));
}

tester();
?>
-- 
Richard Quadling
Twitter : EE : Zend
@RQuadling : e-e.com/M_248814.html : bit.ly/9O8vFY

---

## #51878 — Richard Quadling — 2011-04-12T11:40:22+00:00

URL: https://externals.io/message/51857#51878 · In reply to: #51877

> [1] http://pastebin.com/qLNYtfAw

Updated to http://pastebin.com/cqSEcGpN to include 0 and '' values.

The output is ...

Undefined variable                isset() = false  empty() = true
defined = false
Defined variable null value       isset() = false  empty() = true
defined = true
Defined variable 0                isset() = true   empty() = true
defined = true
Defined variable non-null value   isset() = true   empty() = false
defined = true
Undefined key                     isset() = false  empty() = true
defined = false
Undefined key null value          isset() = false  empty() = true
defined = true
Undefined key non-null value      isset() = true   empty() = false
defined = true
Undefined key 0 value ""          isset() = true   empty() = true
defined = true

Attempting to access any variable where defined = false would be the
only place the `E_NOTICE` is generated.


-- 
Richard Quadling
Twitter : EE : Zend
@RQuadling : e-e.com/M_248814.html : bit.ly/9O8vFY

---

## #51879 — Lars Schultz — 2011-04-12T12:21:40+00:00

URL: https://externals.io/message/51857#51879 · In reply to: #51877

Am 12.04.2011 13:33, schrieb Richard Quadling:
> Notice: Undefined variable
> Notice: Undefined index

To me, these two notices are totally different in severity, but that may 
be because of how i write my code. I'd like to be able to get rid of the 
"Undefined index" Notice in a nice, clean, readable way, because that 
does not bother me (in my style of code). I do wanna be notified if i am 
using an undefined variable, as that implies something wrong on a more 
basic level.


	$x = isset($x)?$x:'default x';

I don't want a construct for this, because I was either lazy or made a 
mistake when I did not define $x initially. -1


	$x = isset($_GET['x'])?$_GET['x']:'default x';

I can see the use for an alternative construct for this though, but it's 
not really a pressing matter to me. +0.5

But that is just me and my code.
Lars
