M
M
Mikhail2018-03-02 00:41:04
PHP
Mikhail, 2018-03-02 00:41:04

How to return an array from a class constructor?

from file 1.php I declare a class

include_once('2.php');
$result = new class1();
print_r($result);

in file 2.php there is a class with a constructor
class class1 {
    public function __construct() {
        $res['1']='1';
        $res['2']='2';
        return($res);
    }
}

in this case, the result of the file output is 1 empty object.
after a bunch of different attempts, the result was:
file 1.php
include_once('2.php');
$result = new class1();
print_r($result->result());

file 2.php
class class1 {
    private $res;
    function __construct() {
        $this->$res['1']='1';
        $this->$res['2']='2';
    }
    public function result() {
        return($this->$res);
    }
}

in this case, as a result, the array is returned, but at the same time, for each line where $this->$res is present, an error is generated stating that the res variable is not declared.
how to do it right so that the array is passed, preferably immediately from the constructor, and no errors occur?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
K
K. A., 2018-03-02
@f_u_s_s

Not sure, but try this:

class class1 {
    private $res;
    public function __construct() {
        $this->res[] = '1';
        $this->res[] = '2';
        return($this->res);
    }
}

and in the second file:
$result = new class1();
print_r($result);

And your errors in the second case arise due to the construction:
$this->$res - replace it as in my example above with $this->res

M
Maxim Fedorov, 2018-03-02
@qonand

By itself, the presence of classes does not mean that you are using an OOP approach. Your code, like the question itself, speaks of a complete lack of understanding of the OOP paradigm. Therefore, it is better to deal with it, read the relevant articles / books, instead of writing a bunch of similar code "on the fly". If you don’t want to understand, then you shouldn’t build a project on objects and everything connected with them at all

A
Alexander, 2018-03-02
@AK-VoronM

Couldn't get past. Tin, colleagues)))
If you really want classes and get data in one call, use static methods.

class MyClass
{
    //Публичный метод для получения данных
    public static function getSomeData()
    {
        $result = self::someAction();
        
        return $result;
    }
    
    //Скрытый служебный метод
    protected static function someAction($data = null)
    {
        //Тут что-то делаем
        return $result;
    }
}

$result = MyClass::getSomeData(); //Так получаем данные. Без фанатизма с конструктором.

No need to be rude, descendants will not forgive you))))
I recommend reading at your leisure: click (without refs).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question