PHP array of objects without access to get methods

Asked

Viewed 546 times

6

I’m trying to access the getters which refer to an object, but this object is in an array, and by no means can I access them. Follow the DAO class (where the mess is taking place and I’m taking the test) and the VO class:

DAO:

<?php
error_reporting(-1); 
ini_set('display_errors', 'On');
define('CONFIG', dirname(dirname(__DIR__)). '/config'. DIRECTORY_SEPARATOR);
define('MODEL_VO', dirname(dirname(__DIR__)). '/model/vo'. DIRECTORY_SEPARATOR);
include(CONFIG . 'conexao.php');
include(MODEL_VO . 'prioridade.php');

Class PrioridadeDao{
    private $conexao;
    private $prioridadeObj;
    private $prioridadeArrayObj = array();

    public function __construct(){
        $this->conexao = new Conexao();
    }

    public function teste(){
        echo "teste";
    }


    public function selectAll(){
        if(!$this->conexao->conecta()){
            exit;
        } else {
            $result = pg_query($this->conexao->conecta(), "SELECT * FROM prioridade");
            while ($consulta = @pg_fetch_array($result)){
                $this->prioridadeObj = new Prioridade($consulta['id'], $consulta['nivel'], $consulta['nome']);
                $this->prioridadeArrayObj[] = $this->prioridadeObj;
            }

            #### Aqui onde a coisa ocorre, no cast aparentemente está certo não consigo é acessar as coisas após ele
            #### por isso usei o var_dump para ver o que tem na saida.

            $this->prioridadeArrayObj = (object) $this->prioridadeArrayObj;
            var_dump($this->prioridadeArrayObj);
            $this->conexao->encerra();
        }
    }
}


Model VO:

<?php
Class Prioridade{
    private $id;
    private $nivel;
    private $nome;

    //public function __construct(){

    //}

    public function __construct($id, $nivel, $nome){
        $this->setId($id);
        $this->setNivel($nivel);
        $this->setNome($nome);
    }

    #GETTERS AND SETTERS
    public function setId($id){
        $this->id = $id;
    }

    public function setNivel($nivel){
        $this->nivel = $nivel;
    }

    public function setNome($nome){
        $this->nome = $nome;
    }

    public function getId(){
        return $this->id;
    }

    public function getNivel(){
        return $this->nivel;
    }

    public function getNome(){
        return $this->nome;
    }
}



As I am doing in MVC I want to use the interactions between the classes correctly. (If someone has a nice tutorial of PHP mvc thank you because the references I have found are confusing me). I spent a lot of time programming with Java (Desktop) and to access the methods is super easy, already in PHP I’m having many difficulties.

Another question, can I do 2 constructor methods in a class that is not even possible in Java? Ex:
1 - public Function __Construct(){}
2 - public Function __Construct($param1, $param2){}

Thank you in advance.
If I replace "var_dump" with "print_r" I have the following result:

stdClass Object ( [0] => Priority Object ( [id:Priority:private] => 1 [level:Priority:private] => 1 [name:Priority:private] => VERY LOW ) [1] => Priority Object ( [id:Priority:private] => 2 [level:Priority:private] => 2 [name:Priority:private] => LOW ) [2] => Priority Object ( [id:Priority:private] => 3 [level:Priority:private] => 3 [name:Priority:private] => NORMAL ) [3] => Priority Object ( [id:Priority:private] => 4 [level:Priority:private] => 4 [name:Priority:private] => HIGH ) [4] => Priority Object ( [id:Priority:private] => 5 [level:Priority:private] => 5 [name:Priority:private] => VERY HIGH ) )

  • And what came in var_dump? Have you tried print_r()? Remove@ from this line: @pg_fetch_array($result)... to handle errors.

  • I didn’t understand the doubt :\

  • @Andrébaill edited the post to show you what appears on print_r. A and apart from @ no mistake occurs, there is all right what I ask is in sequence.

  • you want to access an object within the array?

  • @rray yes want to access the get methods of this object, in the priority class that posted have the get methods, I want through DAO rescue these values of the objects through the GET methods, because I do not want the attributes to be public, to access them directly.

  • Tried somehow to use a foreach ($var as $arr) to access them?

  • So that the cast for Object?

  • @Andrébaill didn’t try no, because I don’t know what the sequence of it looks like. Would it look like: $arr->getNome(); ??? or do I have to create a new variable to receive this value? Our guy this Object business in php is very confusing :(

  • I’m not sure what you’re getting at... But I would try to use foreach($this->priorityArrayObj as $object){ echo $object->field; } - I’m just not sure it will work in your case, it wouldn’t hurt to try! :)

  • @bfavaretto I saw in a post to convert, I thought saying that the type was Object could access the methods somehow. But on the Internet I only get things with direct access nothing with private attribute. I must be searching wrong only can.

  • @Andrébaill you got what I wanted to understand, I was closer than expected, I had not found something that had helped me (only worse rsrs). This your previous comment of foreach helped me a lot, I made a test and this way and I was able to access the get method, which looks for what I need without directly accessing the object attribute, even because it is as private. I’ll post the code.

  • Great. I’ve had this problem many times and solved it using foreach... But there’s also the option @rray posted, which is almost my idea, only organized :) rsrs

  • Thank you @Andrébaill your commitment and dedication were very helpful in solving my problem.

  • For nothing! A disposition.. Whenever you have doubts.. Hug.

Show 9 more comments

1 answer

7


In the method selectAll() it is not necessary to cast the array for Object, the idea is the same of java create an array and then iterate on it, the difference is that you type it with Generics something like Lista<Prioridade> and in php no, but the objects of that type are inside the array.

$this->prioridadeArrayObj = (object) $this->prioridadeArrayObj;

I suggest you return the array at the end of the method, like this.

while ($consulta = pg_fetch_array($result)){
   $this->prioridadeObj = new Prioridade($consulta['id'], $consulta['nivel'], $consulta['nome']);
   $this->prioridadeArrayObj[] = $this->prioridadeObj;
}
$this->conexao->encerra();
return $this->prioridadeArrayObj;

After that take the return of selectAll() and make a foreach.

$dao = new PrioridadeDao();
$itens = $dao->selectAll();
foreach($itens as $item){
   $echo $item->getNivel() .' - '. $item->getNome();
}

Another question, has as I do 2 methods builders in a class that is not even possible in Java? > Ex:

1 - public Function> __Construct(){}

2 - public Function __Construct($param1, $param2){}

PHP does not support Overload so it is not possible to have multiple constructs, however it is possible to have a function/constructor with a variable number of arguments.

In php5.6 you can use:

function funcao(...$param) {

In previous versions use the function func_num_args

Recommended reading

What good is a builder?

It is possible to create classes with two constructors?

How to access Object properties with Names like integers?

  • It looked like what I did, but since I did a direct test at DAO it didn’t curl up like this, but the idea was the same. Now I understand better. D feeling happy now.

  • Great, @rray always gives a strength in my codes too... the logic was the same, but his answer is perfect! But that worked great..

  • Thank you @rray for your unselfish commitment and dedication. Could you just take away my other doubt? Can I have 2 __Construct methods in the same class? One with argument and another unique in java?

  • @Luangabrieldacostarodrigue, updated the answer now.

  • Sure I am in need of a good reading, I have found a lot of old stuff on the internet that often has not helped me. Thank you for that reply @rray , and yes, I will read this information you went through and improve. : Thanks man, hug, now I’ll sleep otherwise tomorrow I won’t be able to go to the job interview rsrsrs.

  • @Luangabrieldacostarodrigue, take a look at php wiki has several tips and materials there;

  • I know the Post is old , but the answer fell like a glove here for me too. Vlw

  • @Henriquefelix glad you were helpful :)

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.