Return 2 things from a function - php

I have a function that returns a multidimensional array, but I also need to return a single value. I am currently using the single value via the global keyword, so I can modify it inside the function.
But I'm wondering if there is another/better way to return 2 values from a function?
Current (pseudo) code:
global $iNumber;
$arrResult;
{do some calculations and queries}
$iNumber = 73;
return $arrResult;
The function that called this function can use the array of arrays, and also the global variable which has been updated to 73.
But is there another/better way to combine or pass these two different values?

You can do it in two ways: to return an array or an object.
Array solution:
function calculate(...) {
//do some stuff
return ['result' => $arrResult, 'iNumber' => $iNumber];
}
Object solution:
function calculate(...) {
//do some stuff
$object = new stdClass();
$object->result = $arrResult;
$object->iNumber = $iNumber;
return $object;
}
stdClass is just an example and you can create your own class for this purpose.

You can make a class and use a class variable.
Something like this:
class Test
{
public $iNumber;
function __construct()
{
# code...
}
public function yourCal()
{
// you calculations
$this->setNumber(73);
return $arrayOfArrays;
}
public function getNumber()
{
return $this->iNumber;
}
public function setNumber($var)
{
$this->iNumber = $var;
}
}
// Use the class in another php file
include 'Test.php';
$test = new Test();
// do calculations
$arrayOfArrays = $test->yourCal();
// get the number
$iNumber = $test->getNumber();
echo $iNumber; // returns 73
print_r($arrayOfArrays); // print your array

Related

Return array variable in PHP

I have a function and I'd like to return a variable to another function.
Can I return the array variable so I can use the variable at other function?
public function update_mdr_pameran() {
//global $araydatamdr;
$this->config->set_item('compress_output', FALSE);
$araydatamdr['mdr_debit'] = trim($this->input->post('mdr_debit'));
$araydatamdr['mdr_debit_npg'] = trim($this->input->post('mdr_debit_npg'));
$araydatamdr['mdr_debit_pl'] = trim($this->input->post('mdr_debit_pl'));
return $araydatamdr;
}
When I try to use $araydatamdr in another function, it became 0.
Am I missing something?
You can achieve this by calling function and setting its return value to another variable.
Method 1 :
class Test extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function update_mdr_pameran() {
//global $araydatamdr;
$this->config->set_item('compress_output', FALSE);
$araydatamdr['mdr_debit'] = trim($this->input->post('mdr_debit'));
$araydatamdr['mdr_debit_npg'] = trim($this->input->post('mdr_debit_npg'));
$araydatamdr['mdr_debit_pl'] = trim($this->input->post('mdr_debit_pl'));
return $araydatamdr;
}
public function test_func() {
$araydatamdr = $this->update_mdr_pameran();
var_dump($araydatamdr);
}
}
Or you can also set $araydatamdr to $this reference.
Method 2 :
class Test extends CI_Controller {
public $araydatamdr;
public function __construct() {
parent::__construct();
$this->araydatamdr = [];
}
public function update_mdr_pameran() {
$this->config->set_item('compress_output', FALSE);
$this->araydatamdr['mdr_debit'] = trim($this->input->post('mdr_debit'));
$this->araydatamdr['mdr_debit_npg'] = trim($this->input->post('mdr_debit_npg'));
$this->araydatamdr['mdr_debit_pl'] = trim($this->input->post('mdr_debit_pl'));
}
public function test_func() {
$this->update_mdr_pameran();
var_dump($this->araydatamdr);
}
}
Cross out the echo $araydatamdr; Arrays can be printed using var_dump or print_r. Also you can return an array in php but personally i prefer to json_encode it first so i return a json as the output of my function something like:
return json_encode($araydatamdr);
Then it's a simple function call.
I don't know your project structure but i am giving general guidance. Apart from that i don't see anything else that could block your function.
I edit my post because i saw the issue is to call the function. There are 2 ways depending where you call it. If the function is in the same class as the other function you want to call it you simple go for :
$result=$this->update_mdr_pameran();
I see that your function has no arguments so you don't need to set any. If it's in another file:
1) include your php file at top like :
require 'myphpclass.php';
*tip make sure your path is right.
2) Create a new class object and then call the function like :
$class= new myClass();
$result=$class->update_mdr_pameran();

How to save result OOP?

I have the following class:
class Algorithm {
public function __constructor($arr){
$this->arr = $arr;
}
public function handle(){
return $this->Q($this->arr[0]); // 1, 2, 3 etc
}
public function Q(){
return 2;
}
public function R(){
return 1;
}
}
I create some instances of class in loop:
foreach($arr as $key){
$objects[] = new Algorithm(["1", "2", "3"]);
}
So, I need to handle all values passed to Algorithm and return state execution. I mean save result from Q and R methods in class.
So in result I need to get so as:
$objects[0]->Q; //1
$objects[1]->Q; //2
$objects[0]->R; //1
$objects[1]->R; //2
After I need to pass result objects in another class B:
$nextHandle = new B($objects);
Where get others result of two functions:
class B {
public function go($objects[0]) {
return 1;
}
public function do($objects[0]) {
return 1;
}
}
In result also return values do()and go()
So, problem is that I don't know how to operate of instances of object and pass these for calculation in another class. Also how to save intermediate states of calculations, I mean methods in each class?
Also one of main thinking is how to pass object with all states in another instance of class, that inside I can get state of element passed object?

A faster way of doing objectToArray

Ive got this snippet of code below which works perfectly fine. I have been profiling it and the bit of code gets used alot of times, so I want to try figure out how to write it in a way that will perform better than the current way its written.
Is there a more efficient way to write this?
function objectToArray($d) {
if (is_object($d)) {
// Gets the properties of the given object
// with get_object_vars function
$d = get_object_vars($d);
}
if (is_array($d)) {
// Return array converted to object Using __FUNCTION__ (Magic constant) for recursive call
return array_map(__FUNCTION__, $d);
}
else {
// Return array
return $d;
}
}
You could implement a toArray() method to the class that needs to be converted:
e.g.
class foo
{
protected $property1;
protected $property2;
public function __toArray()
{
return array(
'property1' => $this->property1,
'property2' => $this->property2
);
}
}
Having access to the protected properties and having the whole conversion encapsulated in the class is in my opinion the best way.
Update
One thing to note is that the get_object_vars() function will only return the publically accessible properties - Probably not what you are after.
If the above is too manual of a task the accurate way from outside the class would be to use PHP (SPL) built in ReflectionClass:
$values = array();
$reflectionClass = new \ReflectionClass($object);
foreach($reflectionClass->getProperties() as $property) {
$values[$property->getName()] = $property->getValue($object);
}
var_dump($values);
depends what kind of object it is, many standard php objects have methods built in to convert them
for example MySQLi results can be converted like this
$resultArray = $result->fetch_array(MYSQLI_ASSOC);
if its a custom class object you might consider implementing a method in that class for that purpose as AlexP sugested
Ended up going with:
function objectToArray($d) {
$d = (object) $d;
return $d;
}
function arrayToObject($d) {
$d = (array) $d;
return $d;
}
As AlexP said you can implement a method __toArray(). Alternatively to ReflexionClass (which is complex and expensive), making use of object iteration properties, you can iterate $this as follow
class Foo
{
protected $var1;
protected $var2;
public function __toArray()
{
$result = array();
foreach ($this as $key => $value) {
$result[$key] = $value;
}
return $result;
}
}
This will also iterate object attributes not defined in the class: E.g.
$foo = new Foo;
$foo->var3 = 'asdf';
var_dump($foo->__toArray());)
See example http://3v4l.org/OnVkf
This is the fastest way I have found to convert object to array. Works with Capsule as well.
function objectToArray ($object) {
return json_decode(json_encode($object, JSON_FORCE_OBJECT), true);
}

PHP object method doesn't behave as I expect

I can't quite understand why the output of this code is '1'.
My guess is that php is not behaving like most other OO languages that I'm used to, in that the arrays that php uses must not be objects. Changing the array that is returned by the class does not change the array within the class. How would I get the class to return an array which I can edit (and has the same address as the one within the class)?
<?php
class Test
{
public $arr;
public function __construct()
{
$this->arr = array();
}
public function addToArr($i)
{
$this->arr[] = $i;
}
public function getArr()
{
return $this->arr;
}
}
$t = new Test();
$data = 5;
$t->addToArr($data);
$tobj_arr = $t->getArr();
unset($tobj_arr[0]);
$tobj_arr_fresh = $t->getArr();
echo count($tobj_arr_fresh);
?>
EDIT: I expected the output to be 0
You have to return the array by reference. That way, php returns a reference to the array, in stead of a copy.
<?php
class Test
{
public $arr;
public function __construct()
{
$this->arr = array();
}
public function addToArr($i)
{
$this->arr[] = $i;
}
public function & getArr() //Returning by reference here
{
return $this->arr;
}
}
$t = new Test();
$data = 5;
$t->addToArr($data);
$tobj_arr = &$t->getArr(); //Reference binding here
unset($tobj_arr[0]);
$tobj_arr_fresh = $t->getArr();
echo count($tobj_arr_fresh);
?>
This returns 0.
From the returning references subpage:
Unlike parameter passing, here you have to use & in both places - to
indicate that you want to return by reference, not a copy, and to
indicate that reference binding, rather than usual assignment, should
be done
Note that although this gets the job done, question is if it is a good practice. By changing class members outside of the class itself, it can become very difficult to track the application.
Because array are passed by "copy on write" by default, getArr() should return by reference:
public function &getArr()
{
return $this->arr;
}
[snip]
$tobj_arr = &$t->getArr();
For arrays that are object, use ArrayObject. Extending ArrayObject is probably better in your case.
When you unset($tobj_arr[0]); you are passing the return value of the function call, and not the actual property of the object.
When you call the function again, you get a fresh copy of the object's property which has yet to be modified since you added 5 to it.
Since the property itself is public, try changing:
unset($tobj_arr[0]);
To: unset($t->arr[0]);
And see if that gives you the result you are looking for.
You are getting "1" because you are asking PHP how many elements are in the array by using count. Remove count and use print_r($tobj_arr_fresh)

PHP function, return by value or by reference?

When I use return statement in PHP, will the result be returned by value or by reference?
Thanks! Andree.
In PHP, everything is returned by value by default (I'm sure there are exceptions to this but I can't think of any atm). Except objects (PHP>5.0) which are passed by reference by default.
Apparently, it is returned by reference. This simple code proofs it.
<?php
class InsideObject
{
public $variable;
}
class OutsideObject
{
private $insideObject;
public function __construct()
{
$this->insideObject = new InsideObject();
$this->insideObject->variable = '1';
}
public function echoVar()
{
echo $this->insideObject->variable;
}
public function getInsideObject()
{
return $this->insideObject;
}
}
$object = new OutsideObject();
$object->echoVar(); // should be 1
$insideObject = $object->getInsideObject();
$insideObject->variable = '2';
$object->echoVar(); // should be 2

Categories