Answer the question
In order to leave comments, you need to log in
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);
class class1 {
public function __construct() {
$res['1']='1';
$res['2']='2';
return($res);
}
}
include_once('2.php');
$result = new class1();
print_r($result->result());
class class1 {
private $res;
function __construct() {
$this->$res['1']='1';
$this->$res['2']='2';
}
public function result() {
return($this->$res);
}
}
Answer the question
In order to leave comments, you need to log in
Not sure, but try this:
class class1 {
private $res;
public function __construct() {
$this->res[] = '1';
$this->res[] = '2';
return($this->res);
}
}
$result = new class1();
print_r($result);
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
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(); //Так получаем данные. Без фанатизма с конструктором.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question