foreach with php and poo

2

I'm learning PHP with POO and I wanted to print an array with foreach with an object and it worked for me:

class padre
{

    function __construct()
    {
        $nombres = ["Perengano", "sutano", "chilindrina"];
        foreach ($nombres as $name) {
            echo "$name <br>";
        }
    }
}
$a = new padre;

But now I want to do it calling the array from an attribute but it does not come out or I do not know if it can be done the way I look.

I hope your help and if you can, some advice to improve my learning in PHP, greetings and thanks in advance =)

    
asked by user23028 28.03.2018 в 07:13
source

1 answer

4

You can do it this way, you declare the structure of the class, but instead of using a __construct method that seeks to give values to a default class you can use a named method; that is to say a function likewise to use a foreach is ideal better to declare an associative array that is to say of key-value

At the end when creating the instance of the class to the object named $ a we can in the last line give an echo to that object by accessing the print method that will return the results of said array

Look at the example

class Datos
{
    protected $nombres;

    function imprimir()
    {
        $this->nombres = array("valor1" => "Perengano","valor2" => "sutano","valor3" => "chilindrina");
        foreach ($this->nombres as $key => $value)
        {
            echo $value.PHP_EOL;
        }
    }
} 

$a = new Datos;
echo $a->imprimir();

The key and value details are for:

  • $ key returns for example $ value1, $ value2 and $ value3
  • $ value returns the values associated with the keys of point one
  • On the other hand, the names of the classes must be capitalized and have reference to the content of said class
  • On the other hand you should always indicate the scope of a property, within which you have public, private and protected; the ideal is that they are not public so that they are not modifiable outside the class that declared them
  • Now if you want to use the constructor to initialize a property at the time of creating the class it would be this way and it remains functional

    class Datos
    {
        protected $nombres;
    
        public function __construct()
        {
            $this->nombres = array("valor1" => "Perengano","valor2" => "sutano","valor3" => "chilindrina");
        }
    
        function imprimir()
        {
            foreach ($this->nombres as $key => $value)
            {
                echo $value.PHP_EOL;
            }
        }
    } 
    
    $a = new Datos();
    echo $a->imprimir();
    
        
    answered by 28.03.2018 / 07:30
    source