PHP: What does the expression "a or b" mean?

Moved through this code:

<?php require_once 'HTTP/Session/Container/DB.php'; $s = new HTTP_Session_Container_DB('mysql://user: password@localhost /db'); ini_get('session.auto_start') or session_start(); //HERE. ?? ?> 

What does this kind of expression mean in PHP? [a OR b]?

 ini_get('session.auto_start') or session_start(); 

Thanks.

+4
source share
5 answers

This expression depends on how or works. It is usually used to check if one of two logical values ​​is true:

 $foo = true or false // true $foo = false or false // false 

It’s great that if the left side of or is true, it never checks the last part, because it does not need it. This means that you can put an expression on each side of or . If the left side results in a negative value (a value that resolves to false ), then the right side will be executed. If the left side results in a positive value that allows true, then the right side will never be executed.

So, to summarize, this is:

 ini_get('session.auto_start') or session_start(); 

identical to this:

 if(!ini_get('session.auto_start')) session_start(); 

since ini_get('session.auto_start') leads to either 0 or 1 , which evaluates to false and true respectively.

+2
source

The or keyword is a logical or statement equivalent to || :

 if ($x < 0 or $y < 0) // the same as: if ($x < 0 || $y < 0) 

The or property is that the second operand is not evaluated if the first returns true:

  if (!isset($var) || $var === null) # ^^^^^^^^^^^^^ # This code is never run if !isset($var) returns false. 

This can be (incorrectly) used to write the code "do something or handle the error":

  do_something() or handle_error() # ^^^^^^^^^^^^^^ # If do_something() returns true, there is no error to handle, # and handle_error() is never executed. 

It could be written more clearly using an explicit if :

 if (!do_something()) handle_error(); 
+3
source

if a permits a value that PHP can convert to true , then b will not execute.

It can be used as a shortcut for if( !a ) b

+2
source

Make function A, if it does not work, function B

you can see it on mysql_query ("jibberish") or die ("mysql can not run query");

+1
source

In your case, if session.auto_start is set to true, do nothing. Otherwise, start a session.

a OR b checks if true, and if b fails.

Thus, basically, this means that a session can only be started if it is not started by default.

+1
source

All Articles