Question:
Is isset($var1)
the same as (!$var1)
?. That is, in the examples that I put below it seems to work the same way: detect if a variable is defined. If they are not the same, when do you use one and the other?
<?php
$var1;
if(!$var1){
echo "si";
}
?>
Same example with isset
<?php
$var1;
if(isset($var1)){
echo "si";
}
?>
This example contains both isset and ! . As you will see when using the ! not checks if a controller exists but… what happens when it doesn't exist. Will it throw a PHP "undefined variable" error?
class Request{
private $_controlador;
private $_metodo;
private $_argumentos;
public function __construct(){
if(isset($_GET['url'])){
$url = filter_input(INPUT_GET, 'url', FILTER_SANITIZE_URL);
$url = explode('/', $url);
$url = array_filter($url);
//toma array url y coge el primer elemento y lo asigna a _controlador.
//Lo mismo con _metodo y argumentos.
$this->_controlador = strtolower(array_shift($url));
$this->_metodo = strtolower(array_shift($url));
$this->_argumentos = $url;
}
if(!$this->_controlador){
$this->_controlador = DEFAULT_CONTROLLER;
}
if(!$this->_metodo){
$this->_metodo = 'index';
}
if(!isset($this->_argumentos)){
$this->_argumentos = array();
}
}
public function getControlador()
{
return $this->_controlador;
}
public function getMetodo()
{
return $this->_metodo;
}
public function getArgs()
{
return $this->_argumentos;
}
}
Answer:
Well, no, it's not the same.
isset()
checks that the variable exists, while !
it just checks that the value is "false".
That is, if you do an isset()
to a variable that doesn't exist, it will return false, but if you do !variableInexistente
you will get a PHP error for using an undefined variable.