Error obtaining properties of a [duplicate] object

1

I'm starting in the world of POO with PHP. When accessing the properties of the object Persona through a getter, its corresponding value does not appear.

The class code is as follows:

<?php
    class Persona{
        public $nombre;
        public $apellido;
        public $dni;

        function setName($nombre){
            $this -> nombre = $nombre;
        }
        function getName(){
            return $this -> nombre;
        }
    }
?>

Then in another archivo.php I create an object of that class and give it some values:

<?php
    require_once("class.php"); // fichero de la clase anterior
    $marcos = new Persona();
    $marcos -> setName('Marcos');
    $marcos -> getName();
?>

If I access this script in my browser I do not see anything at all. But if I modify the code and present it in the following way, it shows me on the Marcos screen.

<?php 

    require_once("class.php");
    $marcos = new Persona();
    $marcos -> setName('Marcos');

?>

<?= 

    $marcos -> getName();

?>

How is this? What is the difference between <?php ?> and <?= ?> ?

    
asked by gmarsi 29.08.2017 в 12:46
source

1 answer

4

What is the difference between <?php ?> and <?= ?> ?

The labels have the following purpose:

  • <?php ... ?> : delimit a block of PHP code.
  • <?= ... ?> : equivalent to <?php echo ...; ?> .

You can see its meaning and usage examples in PHP documentation :

  
  • You can use the abbreviated echo tag for <?= 'imprimir esta cadena' ?> .   It is always enabled in PHP 5.4.0 and later, and is equivalent to    <?php echo 'imprimir esta cadena' ?> .
  •   

    Solution

    In order for your code to work for you, you must use echo to send the value to the browser:

    <?php
    require_once("class.php"); // fichero de la clase anterior
    $marcos = new Persona();
    $marcos -> setName('Marcos');
    /* Enviar al navegador el contenido */
    echo $marcos -> getName();
    /* Mejor aún */
    echo htmlspecialchars($marcos->getName());
    

    It's what you implicitly did when using the <?= ... ?> tag.

        
    answered by 29.08.2017 / 12:48
    source