Problem with objects and functions - PHP

1

I have a class Matriz with 10 rows and 10 columns with several functions. When I create an object of that kind in another class and try to use its methods, I have no problem, but when I try to create a function to use that object, it gives me an error.

$m = new Matriz();
echo $m->getFilas()." filas\n";//Sin problemas
echo $m->getColumnas()." columnas\n";//Sin problemas
function mostrarMatriz(){
for ($i = 0; $i < $m->getFilas(); $i++){//Undefined variable: m

I do not put the rest of the loop because the problem already gives it to me in the initialization. I do not think the solution is to create the object within the function because then, it would restart every time I call the function.

EDITO Now I have a problem with the constructor of Matriz (I modified the constructor to be able to decide the number of rows and * columns **, but that part works well):

private $filas;
private $columnas;
private $matr;
public function __construct($filas, $columnas){
    $matr = array();
    $this->filas = $filas;
    $this->columnas = $columnas;
    for ($i = 0; $i < $filas; $i++){
        for ($j = 0; $j < $columnas; $j++){
            $matr[$i][$j] = new Elemento();
        }
    }
}

Apparently, the object of class Elemento is not created, because when I try to use one of its methods, it returns another error:

    public function comprobarValor($fila, $columna){
        return $this->matr[$fila][$columna]->valor();//Uncaught Error: Call to a member function comprobarValor() on null
    }
    
asked by astaroth 11.03.2017 в 23:46
source

2 answers

0

I'll tell you some things.

A. Regarding the error you have in question

In PHP the functions can receive arguments (simple variables, fixes, etc):

  

Function arguments

     

Any information can be passed to the functions through the   list of arguments, which is a list of delimited expressions   by commas. The arguments are evaluated from left to right.

In your case, the function needs to know the argument with which it will work. If it is not declared within the function and it is not a variable of the global type, then you have to pass it to it when you call the function:

Function:

function mostrarMatriz($m)
{
   for ($i = 0; $i < $m->getFilas(); $i++)
   {
      //...
   }
}

Calling the function:

$m = new Matriz();
mostrarMatriz($m);

With this your problem would be solved.

B. But ...

It is possible to do it in another way. Seen the code, one wonders why not create the function mostrarMatriz within Clase Matriz() ?

It would not be a bad practice to create a class inside a getter of the complete matrix, in fact, this is what the OOP recommends (when we work with classes). In this way your Matrix class would have different ways of obtaining the data. Just as you have a method getFilas() , getColumnas() , you could have a method getMatriz() that would return the matrix.

For this the function should have a return.

EDIT:

Possible Model of a Parent Class

class Matriz 
{
    private $filas;
    private $columnas;

    /* 
        *Constructor con parámetros los cuales deben ser pasados 
        * cuando se crea una instancia de la clase
        * usando por ejemplo: $m = new Matriz ("10", "60");
        * nótese que el tipo de dato puede ser otro que String, indicándolo 
        * debidamente a la clase
    */

    public function __construct($filas, $columnas) 
    {
        $this->filas = $filas;
        $this->columnas = $columnas;
        //... todas las demás variables que formarán parte de la clase y que se reciben en parámetro
        // ... las demás, ejemplo las que devuelven los métodos públicos no necesitan declararse
        // ... aquí sólo las variables que la clase necesita *conocer* para trabajar con ellas
    }

    //En este caso el método no necesita parámetros
    public function getMatriz() 
    {

        for ($i = 0; $i < $this->filas; $i++)
        {
        //... aquí se crea una representación de la matriz en una variable o lo que se quiera
        // es lo que se enviará en el return
        }
        return $variableconcatenadaenelbuclefor
    }


    public function getFilas() 
    {
        return $this->filas;

    }


    public function getColumnas() 
    {
        return $this->columnas;

    }
}

As you see, in the class the other methods that the constructor do not receive any parameter, and we can access the rows / columns received in the constructor using the pseudo variable $this .

Example of use:

//Se pasan los valores al contructor, en este caso los valores filas y columnas
$m = new Matriz ("10", "50");
echo "Filas: ". $m->getFilas();
echo "Columnas: ". $m->getColumnas();
echo "Matriz: ". $m->getMatriz();

With this implementation the code would be easier to maintain and if you have to repeat the matrix sample from several files, you would do it with two lines of code, otherwise, in each place where you need to show it, you would have to repeat the function that opens the loop for.     
answered by 12.03.2017 / 01:58
source
0

That happens to you because the variable $m defines it outside the function. A function "isolates" the variables, so the block for can not "see" a $m .

The solution is to pass $m as a parameter of the function mostrarMatriz() , like this:

function mostrarMatriz ($m) {  

The rest of the code would remain the same.

    
answered by 12.03.2017 в 00:10