PHP method to get values dynamically from an array object property - php

In this class, is it possible to get dynamically a value from the array?
class MyClass {
private $array_data;
function __construct() {
$this->array_data['first']['a'] = '1';
$this->array_data['second']['b'] = '2';
$this->array_data['third']['c'] = '3';
}
public function getIndexValue($index){
return $this->{'array_data' . $index};
}
}
$MyClass = new MyClass();
// Prints NULL, but i expect '1'
var_dump($MyClass->getIndexValue("['first']['a']"));

Here's a simple solution. Rather than passing in a string for the indexes, you pass in an array.
public function getIndexValue(array $indexes) {
// count the # of indexes we have
$count = count($indexes);
// local reference to data
$data = $this->array_data;
for ($i = 0; $i < $count; $i++)
{
// enter the array at the current index
$data = $data[$indexes[$i]];
}
return $data;
}
And then rather than a string, you'd pass in an array:
$MyClass->getIndexValue(['first', 'a'])

Related

How to debug an issue in the code sum of digit?

I am having an issue in the code
Warning: Cannot use a scalar value as an array in /opt/lampp/htdocs/programe/sumDigit.php on line 410
Here is the code:
class SumOfDigit{
public $sum = 0;
public $num ;
public function __construct($n) {
$this->num = $n;
}
public function equation() {
for($i= 0; $i<strlen($this->num); $i++){
$this->num[$i] = array_map('intval', str_split($this->num));
$this->sum += $this->num[$i];
print_r($this->sum);
}
}
}
$obj = new SumOfDigit(232);
echo $obj->equation();
Based on the name of your class I assume you want to sum the digits in the value you create an object of the class with. In that case, you can simplify your code by using array_sum on the output of str_split:
Class SumOfDigit{
public $sum = 0;
public $num;
public function __construct($n){
$this->num = $n;
}
public function equation(){
$this->sum = array_sum(str_split($this->num));
return $this->sum;
}
}
$obj = new SumOfDigit(232);
echo $obj->equation();
Output:
7
Demo on 3v4l.org
In your code first you assigned a integer to "num"
$this->num = $n;
and inside the function equation() you are using the same value as array as well
$this->num[$i] = array_map('intval', str_split($this->num));
Change the name any one of the variable and try.
Hope it helps

Change variable returned as reference from object method PHP

I would like overwrite array element returned as reference. I can do it like this:
$tmp = $this->event_users_details;
$tmp = &$tmp->firstValue("surcharge");
$tmp += $debt_amount;
I would do it in one line like:
$this->event_users_details->firstValue("surcharge") += $debt_amount;
but I get Can't use method return value in write context
Where $this->event_users_details is a object injected in constructor.
My function look like:
public function & firstValue(string $property) {
return $this->first()->{$property};
}
public function first() : EventUserDetails {
return reset($this->users);
}
and users is a private array.
You can't do it without temporary variable stores "surcharge" value.
From documentation:
To return a reference from a function, use the reference operator & in both the function declaration and when assigning the returned value to a variable:
<?php
function &returns_reference()
{
return $someref;
}
$newref =& returns_reference();
?>
I checked it with this code:
class Item
{
public $foo = 0;
}
class Container
{
private $arr = [];
public function __construct()
{
$this->arr = [new Item()];
}
public function &firstValue($propNme)
{
return $this->first()->{$propNme};
}
private function first()
{
return reset($this->arr);
}
}
$container = new Container();
var_dump($value = &$container->firstValue('foo')); // 0
$value += 1;
var_dump($container->firstValue('foo')); // 1

How can I get objects from an array of specific objects?

I'm new in PHP-POO. I would like to retrive objects from an array and access to that object properties.
My intent code is:
require_once("../modelo/ClubDAO.php");
require_once("../modelo/Club.php");
require_once("../utils/ArrayList.php");
$clubs = new ArrayList();
/* GET ALL THE CLUBS OF THE DATABASE (WORKS GOOD)*/
$clubs = ClubDAO::get_instancia()->getAllClubs();
for($i = 0; $i < $clubs->size(); $i++)
{
$club = new Club();
$club->getNif(); /* HERE I CAN ACCESS TO THE FIELDS */
$club = $clubs->item($i);
$club->/*HERE I CAN'T ACCES TO THE FIELDS OF THE CLASS*/
}
ArrayList class is an encapsulation of a simple array, for me it's easier to work with, here the code:
class ArrayList {
var $array;
public function ArrayList() {
$this->array = array();
}
public function addItem($item){
$this->array[] = $item ;
}
public function toString(){
$cadena = "";
foreach ($this->array as $item) {
$cadena .= $item;
}
return $cadena;
}
public function delete($item){
unset($this->array[$item]);
}
public function item($item){
return $this->array[$item];
}
public function size(){
return count($this->array);
}
}
You are overwriting your variable:
$club = $clubs->item($i);
So it will not be the object you expect any more.

i am trying to make a array of a object in php

I'm trying to make an array of Spells.
My current code
class Spell
{
public $bomb = 0;
public $fire = 0;
function Spell()
{
$this->bomb =0;
$this->fire =0;
}
}
And I declare the object spell on my game class like this
class game
{
public $Spell=array();
function Game()
{
$this->Spell[0] = new Spell();
}
function s()
{
$this->Spell[1]->$bomb = $load($x)
$this->Spell[1]->$fire = $load($x);
$this->Spell[2]->$bomb = $load($y)
$this->Spell[3]->$bomb = $load($z)
}
}
It returns this error -- Warning: Creating default object from empty value in...
I guess this isn't the best way to create an array of objects. How to do it properly?
EDIT:
x y z, just return strings
The problem is that you have not created objects for $this->Spell[1], $this->Spell[2] and $this->Spell[3]. If you change your Game() constructor to this:
function Game()
{
for ($i = 1; $i <= 3; $i++) {
$this->Spell[$i] = new Spell();
}
}
It should probably work fine.
You seem to have more than just one problems in your code.
However, I will discuss the one you have asked the question for.
Instead of
$this->Spell[1]->$bomb = something;
Use
$this->Spell[1]->bomb = something;
Second, What do you intend to do by using $load($y)?
If you're using a function named "load", use load($y)
you must create object, then use it, look:
class Spell
{
public $bomb = 0;
public $fire = 0;
function __construct()
{
$this->bomb =0;
$this->fire =0;
}
}
class game
{
public $Spell=array();
function s()
{
$this->Spell[1] = new Spell();
$this->Spell[1]->bomb = 0 ; //or other value
}
}
<?php
class Spell
{
public $bomb = 0;
public $fire = 0;
function Spell()
{
$this->bomb =0;
$this->fire =0;
}
}
class game
{
public $Spell=array();
function Game($index)
{
$this->Spell[$index] = new Spell();
echo 'constructer called';
}
function s()
{
$this->Spell[1]->bomb = $load($x);
$this->Spell[1]->fire = $load($x);
$this->Spell[2]->bomb = $load($y);
$this->Spell[3]->bomb = $load($z);
}
}
$ob = new game();
//$ob->Game(1); to pass the index for array.
?>
You are using lots of undefined stuff, I would say the half of your script is missing.
I just added the comments down here:
class game
{
public $Spell=array();
function Game()
{
$this->Spell[0] = new Spell();
}
function s()
{
/**
down here you are using these undefined "variables":
$bomb
$load
$x
$y
$z
undefined means, you are using a varible which was not declared. so it´s just null.
I tried to fix it:
**/
$x = 1;
$y = 2;
$z = 3;
$this->Spell[1] = new Spell();
$this->Spell[2] = new Spell();
$this->Spell[3] = new Spell();
$this->Spell[1]->bomb = load($x); // add ;
$this->Spell[1]->fire = load($x);
$this->Spell[2]->bomb = load($y)
$this->Spell[3]->bomb = load($z)
}
}
function load($v)
{
return $v * 2;
}

PHP many objects with one Class

I'm very new with PHP and OOP techniques.
So I have no problem creating a object like so:
$member1 = new Member('person 1');
But is there a way to return a bunch of objects. So that I can iterate through them and put them in the DOM?
class Example
{
public function getPeople()
{
$objs = array();
for($i = 0; $i < 10; $i++)
{
$obj[] = new Person('Person ' . ($i + 1));
}
return $objs; // returning an array of Person objects
}
}
$example = new Example();
foreach($example->getPeople() as $person)
{
// Do something with $person
}
In order to get objects, one possible way is to use array :-
$members = new members( array(...));
// you can assess any member via $members->members[$some_id]
// class to return list of members
class members ()
{
public $members = array();
public function __construct( array $ids)
{
foreach ($id as $id)
{
$this->members[$id] = new Member($id);
}
}
}
class member()
{
public function __construct($id)
{
// any other thing you want to do
}
}

Categories