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.
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With