Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

Came across 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 express mean in PHP? [ a OR b] ?

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

Thanks.

like image 918
gilzero Avatar asked Jan 16 '23 06:01

gilzero


2 Answers

The keyword or is the "logical or" operator, equivalent to ||:

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

A property of or is that the second operand is not evaluated if the first one returns true:

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

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

  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();
like image 199
Ferdinand Beyer Avatar answered Jan 18 '23 23:01

Ferdinand Beyer


That expression relies upon the way the or works. It's usually used to check if either one of two booleans are true:

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

The cool thing is that if the left part of the or is true, it never checks the latter part because it doesn't need to. That means that you can put an expression on each side of the or. If the left part results in a negative value (a value that resolves to false) then the right part will be executed. If the left part results in a positive value, one that resolves to true, then the right part will never be executed.

So to summarize, this:

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

is identical to this:

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

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

like image 34
Hubro Avatar answered Jan 18 '23 23:01

Hubro