PHP : Get array from customs Objects functions - php

I search for an php function which would do the following process:
class Item{
private $id;
public function __construct($id){
$this->id = $id
}
public function foo(){
return 'Item_'.$this->id;
}
}
my_array = array();
$my_array[] = new Item(1);
$my_array[] = new Item(2);
$results = thefunctionimlookingfor($my_array, 'foo');
//which give :
//$results = {'Item_1', 'Item_2'}
Does anyone knows this function name?

$results = array_map(function(Item $item) { return $item->foo(); }, $my_array);
And if you really need to have that function:
function applyMethod($data, $method) {
return array_map(function($item) use ($method) {
return $item->$method();
}, $data);
}
$result = applyMethod($my_array, 'foo');

Related

Set anonymous class as parameter of a function

I am writing an small ODM for Mongodb in PHP by PhpStorm. At the aggregate query:
$value = $this->creditRepo->execute(AggregateQueryBuilder::create()->project('name', 'ts')->take(10)->toQuery(),
new class{
public ?string $name;
});
the second parameter is an anonymous class. And inside of execute() function:
function execute(AggregateQuery $query, $class): ArrayObject
{
$result = $this->_collection->aggregate($query->getPipeline(), $query->getOptions());
$returnArray = new ArrayObject();
foreach ($result as $item){
$itemx = App::jsonMapper()->map($item, new $class); // $itemx is instance of $class
$returnArray->append($itemx);
}
return $returnArray;
}
The result in caller script:
$value = $this->creditRepo->execute(AggregateQueryBuilder::create()
->project('name', 'ts')->take(10)->toQuery(), new class{
public ?string $name;
});
$d = $value->getArrayCopy();
$d[0]-> // not type hint, I want it hint to me the <name>
Can PhpStorm know the output of the execute() that I can type hint the output of it?
[Edit]
I have try with function array_map
$value = $this->creditRepo->execute(AggregateQueryBuilder::create()
->project('name', 'ts')->take(10)->toQuery());
$temp = new class{
public ?string $name;
};
$output = array_map(static function ($item) use ($temp) {
$temp->name = $item['name'];
return $temp;
}, (array)$value);
$output[0]->name // type hinted
and I want to write a function that PhpStorm know that return like array_map how to do it?

PHP: Pass an array by reference in a class and use it in other methods

I've the following snippet:
public function __construct($s, $e, &$v, &$rv, $needle, $parser, $id) {
$this->start = $s;
$this->end = $e;
$this->vett = $v;
$this->resVett = &$rv;
$this->id = $id;
$this->needle = $needle;
$this->parser = $parser;
}
public function pushResult($result) {
$this->resVett[] = $result;
}
When I call pushResult the value is properly inserted but the original array, the one referenced by rv, is not affected.
Have you any idea of what could be the problem?
maybe the problem relies elsewhere. I checked your code with an easy example
<?php
class Example {
public $value = [];
public $reference = [];
public function __construct($value, &$reference) {
$this->value = $value;
$this->reference =& $reference;
}
public function pushResult($result) {
$this->reference[] = $result;
$this->value[] = $result;
}
}
$value = ['test'];
$reference = ['test'];
$example = new Example($value, $reference);
$example->pushResult('result');
echo 'Is Value variable same?';
var_dump($value === $example->value);
echo 'Is Reference variable same?';
var_dump($reference === $example->reference);
and passing the reference like you do it should work

how to create an object with only filtered content in PHP OOP

I have created a class with constructor in php which filter xml file. But the object created take all xml data. How can I avoid that?
Thank you for your help!
My code:
class Property {
public $xmlClass;
public $elemClass = '';
public $result_array = [];
public $data = '';
public function __construct($xml,$elem) {
$this->xmlClass=$xml;
$this->elemClass=$elem;
foreach($xml->list->movie as $value) {
$data = $value->$elem;
$result_array[] = $data;
}
print_r($result_array); //here everything is ok
}
}
$result_title = new Property('title');
print_r($result_title); //here object takes all data, not only filtered
$result_title is an object with a lot of props. Among them there's your initial xml as you assign it to xmlClass property.
To get the desired data you need to store it in a class property, you already declare it ($result_array).
So, a proper code could be:
class Property {
public $xmlClass;
public $elemClass = '';
public $result_array = [];
public $data = '';
public function __construct($xml,$elem) {
$this->xmlClass=$xml;
$this->elemClass=$elem;
foreach($xml->list->movie as $value) {
$data = $value->$elem;
// add data to a class property `result_array`
$this->result_array[] = $data;
}
}
// get value of `result_array` with this method
public function getResultArray()
{
return $this->result_array;
}
}
$result_title = new Property('title');
print_r($result_title->getResultArray());
The reason for this is these two lines:
$this->xmlClass=$xml;
$this->elemClass=$elem;
You are assigning them to the object. You can just save the result_array to a property of the object and access that:
class Property {
public $xmlClass;
public $elemClass = '';
public $result_array = [];
public $data = '';
public function __construct($xml,$elem) {
$this->xmlClass=$xml;
$this->elemClass=$elem;
foreach($xml->list->movie as $value) {
$data = $value->$elem;
$result_array[] = $data;
}
$this->titles = $result_array);
}
}
$object = new Property('title');
print_r($object->titles);

PHP object is not being created

I have received the following error:"Fatal error: Call to a member function session_type() on a non-object".
Supposedly I'm not creating an object in the variable "$tabsessiontype2". I don't see the reason why the object isn't created. Thanks for you help.
Here is my TeacherController.php
if(isset($_POST['search']) && $_POST['sessiontype_name']){
$tabsessiontype2=Db::getInstance()->select_session_type2($_POST['sessiontype_name']);
if($tabsessiontype2->session_type()=='X'){
$view='teacher.php';
}
elseif($tabsessiontype2->session_type()=='XO'){
$view='teacherxo.php';
}
elseif($tabsessiontype2->session_type()=='note'){
$view='teachernote.php';
}
}
This is the function I call:
public function select_session_type2($name_session_type) {
$query = "SELECT * FROM session_types WHERE session_types.name_session_type='$name_session_type'";
$result = $this->_db->query($query);
$tableau = array();
if ($result->rowcount()!=0) {
while ($row = $result->fetch()) {
$tableau[] = new Sessiontype($row->code_session_type,$row->name_session_type,$row->quarter_session_type,$row->code_lesson,$row->session_type);
}
}
return $tableau;
}
Here is the SessionType class:
class SessionType{
private $_code_session_type;
private $_name_session_type;
private $_quarter_session_type;
private $_code_lesson;
private $_session_type;
public function __construct($code_session_type,$name_session_type, $quarter_session_type, $code_lesson,$session_type){
$this->_code_session_type = $code_session_type;
$this->_name_session_type = $name_session_type;
$this->_quarter_session_type = $quarter_session_type;
$this->_code_lesson = $code_lesson;
$this->_session_type = $session_type;
}
public function code_session_type(){
return $this->_code_session_type;
}
public function name_session_type(){
return $this->_name_session_type;
}
public function quarter_session_type(){
return $this->_lastname;
}
public function code_lesson(){
return $this->_email_student;
}
public function session_type(){
return $this->_session_type;
}
}
It looks like the function select_session_type2 is returning an array:
$tableau = array();
if ($result->rowcount()!=0) {
while ($row = $result->fetch()) {
$tableau[] = new Sessiontype($row->code_session_type,$row->name_session_type,$row->quarter_session_type,$row->code_lesson,$row->session_type);
}
}
return $tableau;
and you are expecting an object:
$tabsessiontype2=Db::getInstance()->select_session_type2($_POST['sessiontype_name']);
if($tabsessiontype2->session_type()=='X'){
$view='teacher.php';
}

PHP OOP - return arrays into class(?)

I'm trying to use OOP ways. I have bunch of methods that return same format of array. I want to guarantee that user of this class knows what will be returned. How would I go about doing that? Please forgive me as I'm not sure of correct terminologies to describe my problem.
class myModel {
public function getArray1(){
$data = array();
$id = array();
....
return array('data'=>$data, 'id'=>$id); <== HOW TO GUARANTEE RETURN FORMAT
};
public function getArray2(){
$data = array();
$id = array();
....
return array('data'=>$data, 'id'=>$id); <== HOW TO GUARANTEE RETURN FORMAT
};
public function getArray3(){
$data = array();
$id = array();
....
return array('data'=>$data, 'id'=>$id); <== HOW TO GUARANTEE RETURN FORMAT
};
}
You can try to define additional class for returning value:
class returnArray {
$data = array();
$id = array();
function construct($data,$id) {
$this->data = $data;
$this->id = $id;
}
}
//...
public function getArray1(){
$data = array();
$id = array();
....
return new returnArray('data'=>$data, 'id'=>$id);
};
Then You can add accessors to the returnArray class or leave it as public if You want or even implement __toString() if necessary.

Categories