get member value from object inside array in php - php

Can't seem to find the answer for this question: how to get a specific value (member value) from an array of objects?
My code is very simple:
$people = array();
class Person {
public $id;
public $name;
public $family_name;
public $dob;
public $image;
public function __construct($id, $name, $family_name, $dob, $image){
$this->$id = (string) $id;
$this->$name = (string) $name;
$this->$family_name = (string) $family_name;
$this->$dob = (string) $dob;
$this->$image = (string) $image;
}
public function get_id(){
return $this->id;
}
}
for ($i=0;$i<$no_clients;$i++)
{
array_push($people, new Person($_SESSION['user_clients'][$i]['client_id'], $_SESSION['user_clients'][$i]['client_name'], $_SESSION['user_clients'][$i]['client_family_name'], $_SESSION['user_clients'][$i]['client_dob'], ROOT_URL.$_SESSION['user_clients'][$i]['client_img']));
}
now I would like to get the id of one of the person from within the people array
$error = $people[$i]->get_id(); //doesn't seem to work
//not getting a value back even though the session variable is correct
as you've probably seen, I'm a PHP newbie so any advice would be great.
Thanks

Your constructor is wrong (no $ sign in front of the properties)
$people = array();
class Person {
public $id;
public $name;
public $family_name;
public $dob;
public $image;
public function __construct($id, $name, $family_name, $dob, $image){
$this->id = (string) $id;
$this->name = (string) $name;
$this->family_name = (string) $family_name;
$this->dob = (string) $dob;
$this->image = (string) $image;
}
public function get_id(){
return $this->id;
}
}
for ($i=0;$i<$no_clients;$i++)
{
$p=new Person($_SESSION['user_clients'][$i]['client_id'], $_SESSION['user_clients'][$i]['client_name'],
$_SESSION['user_clients'][$i]['client_family_name'],
$_SESSION['user_clients'][$i]['client_dob'],
ROOT_URL.$_SESSION['user_clients'][$i]['client_img']);
//print_r($p); //--> check your object
array_push($people, $p);
}
//print_r($people);
Array ( [0] => Person Object ( [id] => 1 [name] => M [family_name] => C [dob] => 2011-07-21 [image] => image/1_margaret.jpg ) )
EDIT:
Reset that $i counter as probably it's last value was 1. Even better use a foreach loop:
foreach ($people as $person){
echo $person->get_id();
}

Your constructor code is not correct, you're incorrectly referencing your properties. Remove the $ from the start of the property names.
Eg change
$this->$id = $id
to
$this->id = $id

Related

Is there a cleaner way of creating an array?

My php example returns an array that works, but I would like to keep everything inside "class CreateAccount".
This is the way I do it today, and it doesn't look so good but it works. Is there a better way of doing it?
<?php
class CreateAccount {
public function __construct($id,$namne,$fromdate,$group,$comment,$firstnamne,$org,$sid,$todate)
{
$this->countrows = null;
$this->id = $id;
$this->namne = $namne;
$this->fromdate = $fromdate;
$this->group = $group;
$this->comment = $comment;
$this->firstname = $firstnamne;
$this->org = $org;
$this->sid = $sid;
$this->todate = $todate;
}
}
/* Fill your Contact Object */
$contact = new CreateAccount("x6529","Jon Doe","2019-01-16","STD_GROUP","Guest User","Helen Doe","HQ","200410201234","2019-01-17");
/* Set your parameters for the request */
$params = array(
"application" => 'api',
"account" => $contact,
);
print_r($params);
?>
Array
(
[application] => api
[account] => CreateAccount Object
(
[countrows] =>
[id] => x6529
[namne] => Jon Doe
[fromdate] => 2019-01-16
[group] => STD_GROUP
[comment] => Guest User
[firstname] => Helen Doe
[org] => HQ
[sid] => 200410201234
[todate] => 2019-01-17
)
)
PHP have a function get_object_vars to get all the properties of a object. And because you're making dynamic properties in constructor. So, we defined a method getAccount which will get all the properties in an array $properties then we iterate through this and put all info in one array $account and finally we return this array.
<?php
class CreateAccount {
public function __construct($id,$namne,$fromdate,$group,$comment,$firstnamne,$org,$sid,$todate)
{
$this->countrows = null;
$this->id = $id;
$this->namne = $namne;
$this->fromdate = $fromdate;
$this->group = $group;
$this->comment = $comment;
$this->firstname = $firstnamne;
$this->org = $org;
$this->sid = $sid;
$this->todate = $todate;
}
public function getAccount()
{
$properties = get_object_vars($this);
$account = [];
foreach($properties as $property)
{
$account[$property] = $this->{$property};
}
return $account;
}
}
/* Fill your Contact Object */
$contact = new CreateAccount("x6529","Jon Doe","2019-01-16","STD_GROUP","Guest User","Helen Doe","HQ","200410201234","2019-01-17");
/* Set your parameters for the request */
$params = array(
"application" => 'api',
"account" => $contact->getAccount(),
);
print_r($params);
?>
I ended up doling like this:
class CreateAccount {
public function __construct($application,$id,$name,$fromdate,$group,$comment,$firstname,$org,$sid,$todate)
{
$this->application = $application;
$this->gastkonto['countrows'] = null;
$this->gastkonto['id'] = $id;
$this->gastkonto['name'] = $name;
$this->gastkonto['fromdate'] = $fromdate;
$this->gastkonto['group'] = $group;
$this->gastkonto['comment'] = $comment;
$this->gastkonto['firstname'] = $firstname;
$this->gastkonto['org'] = $org;
$this->gastkonto['sid'] = $sid;
$this->gastkonto['todate'] = $todate;
}
}
/* Fill your Contact Object */
$contact = new CreateAccount("api","x6529","Jon Doe","2019-01-16","STD_GROUP","Guest User","Helen Doe","HQ","200410201234","2019-01-17");
print_r($contact);

How to pass array to a class in php?

class User{
public $name ;
public $age ;
public $height ;
public $weight ;
function __construct($name,$age,$height,$weight){
$this->age = $age;
$this->name = $name;
$this->height = $height;
$this->weight = $weight;
}
public function ispis(){
echo $this->age;
}
}
$question_array = [new User ("Ivan","22","174","68"), new
User("Luka","23","174","68") ];
$daniel = new User($question_array);
//$daniel = new User("ivan","22");
$daniel->ispis();
So when i call this function ispis() it doesn't do anything but when i echo inside function __constructor it shows correct values of everything entered. Also when i comment first three lines above //$daniel = new User("ivan","22"); line and uncomment this, ispis() works just fine. Would be nice if someone could explain to me why this is happening. Tnx in advance :)
By the looks of your code you're trying to pass two new User instances into a new user ("daniel").
So basically User is expecting 4 arguments (age, name, height, weight). You've created Luka and Ivan correctly, but you're passing those two Users as arguments when trying to create Daniel. You're giving it Luka and Ivan when it wants age, name, height and weight.
If you simply want to pass an array to the constructor, just pass it as an argument on the new instance:
<?php
class User {
public $name;
public $age;
public $height;
public $weight;
function __construct($args){
$this->age = $args['age'];
$this->name = $args['name'];
$this->height = $args['height'];
$this->weight = $args['weight'];
}
function getAge() {
return $this->age;
}
}
$question_array = [
'name' => 'Daniel',
'age' => '22',
'weight' => '174',
'height' => '68'
];
$daniel = new User($question_array);
echo $daniel->getAge(); // 22
?>
Your question appears a little ambiguous, but perhaps you want to create an object from an array of arguments.
<?php
class User {
public $name;
public $age;
public function __construct($name, $age)
{
$this->name = $name;
$this->age = $age;
}
public function echoAge()
{
echo $this->age;
}
}
$args = ['Leonard', 21];
$bones = new User(...$args);
$bones->echoAge();
Output:
21
Robert just answered, and his method is one that i use in a personal MVC to define construct or in another way there is also this method that i use always in my MVC :P...
Btw i think Ivan you are doing some confusion with classes...
class User{
public $name ;
public $age;
public $height ;
public $weight ;
function __construct($array){
if (is_array($array)){
foreach($array as $k=>$v){
$this->$k = $v;
}
}
}
public function ispis(){
print 'NAME :' .$this->name .' AGE : ' .$this->age.' HEIGHT : ' .$this->height .' WEIGHT : ' .$this->weight.'<br>';
}
}
$arrayOne = ['name'=>"Ivan",'age'=>"22",'height'=>"174",'weight'=>"68"];
$arrayTwo = ['name'=>"Luke",'age'=>"23",'height'=>"174",'weight'=>"68"];
$ivan = new User($arrayOne);
$luka = new User($arrayTwo);
$ivan->ispis();
$luka->ispis();

How to push array into array using php class

i would like to push some arrays into arrays and save it in a session.
And i tried to do this in a php class. I'm new to that so i made some mistakes and can't help me out.
my index.php:
<?php
session_start();
include("./cart.php");
//bezeichnung, preis, attribut
$myOrder = new Cart('17', 0.50, 'Book1');
$myOrder1 = new Cart('18', 1.50, 'Book2');
$_SESSION['products'] = array();
array_push($_SESSION['products'], $myOrder, $myOrder1);
echo '<pre>';
print_r($_SESSION['products']);
echo '</pre>';
my cart.php:
<?php
class Cart {
private $name;
private $price;
private $attr;
public function __construct($name, $price, $attr) {
$this->name = $name;
$this->price = $price;
$this->attr = $attr;
}
public function getName(){
return $this->name;
}
public function getPrice(){
return $this->price;
}
public function getAttr(){
return $this->attr;
}
}
i get something like this:
The part :Cart:private is really not good. This should be juest name,price and attr. I think i'm pushing the whole object into the array. How can i avoid this ?
Array
(
[0] => Cart Object
(
[name:Cart:private] => 17
[price:Cart:private] => 0.5
[attr:Cart:private] => Book1
)
[1] => Cart Object
(
[name:Cart:private] => 18
[price:Cart:private] => 1.5
[attr:Cart:private] => Book2
)
)
You can do a public method in your Cart class that will return all needed properties as an array.
class Cart {
private $name;
private $price;
private $attr;
public function __construct($name, $price, $attr) {
$this->name = $name;
$this->price = $price;
$this->attr = $attr;
}
public function getName(){
return $this->name;
}
public function getPrice(){
return $this->price;
}
public function getAttr(){
return $this->attr;
}
public function toArray(){
return array(
'name' => $this->getName(),
'price' => $this->getPrice(),
'attr' => $this->getAttr(),
);
}
}
Now in your index.php you can do:
array_push($_SESSION['products'], $myOrder->toArray(), $myOrder1->toArray());

Cannot use object of type __PHP_Incomplete_Class as array (Session Related?)

I have 3 separate files, item.php, proposal.php and output.php - this is supposed to be a cart like application, the idea is to for the user to select an item and the item in to the Proposal class... however I am running in to the following error:
Fatal error: Uncaught Error: Cannot use object of type __PHP_Incomplete_Class as array in C:\xampp\htdocs\proposal.php:12 Stack trace: #0 C:\xampp\htdocs\output.php(9): Proposal->addItem(Object(Item)) #1 {main} thrown in C:\xampp\htdocs\proposal.php on line 12
I've searched around SO & Google, and tried various things including placing session_start() before the includes for item.php and proposal.php, however that did not solve the issue, the error just changed to:
Cannot use object of type Proposal as array
Any ideas? Running PHP 7.0.9
item.php
<?php
class Item {
protected $id;
protected $name;
protected $manufacturer;
protected $model;
protected $qty;
protected $serial;
public function __construct($id,$name,$manufacturer,$model,$qty,$serial) {
$this->id = $id;
$this->name = $name;
$this->manufacturer = $manufacturer;
$this->model = $model;
$this->qty = $qty;
$this->serial = $serial;
}
public function getId() {
return $this->id;
}
public function getName() {
return $this->name;
}
public function getManufacturer() {
return $this->manufacturer;
}
public function getModel() {
return $this->model;
}
public function getQty() {
return $this->qty;
}
public function getSerial() {
return $this->serial;
}
}
proposal.php
class Proposal {
protected $items = array();
public function __construct() {
$this->items = isset($_SESSION['proposal']) ? $_SESSION['proposal'] : array();
}
public function addItem(Item $item) {
$id = $item->getId();
// the following line is line 12 of proposal.php
if(isset($this->items[$id])) {
$this->items[$id]['qty'] = $this->items[$id]['qty'] + $item->getQty();
}
else {
$this->items[$id] = $item;
}
}
}
output.php
session_start();
include('item.php');
include('proposal.php');
$item = new Item($_GET['id'],$_GET['name'],$_GET['manufacturer'],$_GET['model'],$_GET['qty'],$_GET['serial']);
$proposal = new Proposal();
$proposal->addItem($item);
$_SESSION['proposal'] = $proposal;
// view output in array/object format if session variable set
if(isset($_SESSION['proposal'])) { print '<pre>' . print_r($_SESSION['proposal'],1) . '</pre>'; }
EDIT: I believe this issue may be session related because the error does not appear until the 2nd run.
Output on first run is:
Proposal Object
(
[items:protected] => Array
(
[25] => Item Object
(
[id:protected] => 25
[name:protected] => Computer
[manufacturer:protected] => Dell
[model:protected] => Alienware
[qty:protected] => 11
[serial:protected] => 12345678
)
)
)
session_start();
include('item.php');
include('proposal.php');
Your session is initialized before classes have been declared.
This is leading to __PHP_Incomplete_Class.
Problem with "Cannot use object of type Proposal as array":
public function __construct() {
$this->items = isset($_SESSION['proposal']) ? $_SESSION['proposal'] : array();
}
If your session contains key proposal, you are using it as storage variable, but this is initialized as instance of Proposal in output.php:
$proposal = new Proposal();
$proposal->addItem($item);
$_SESSION['proposal'] = $proposal;
One way to avoid this is to create a session singleton of Proposal:
class Proposal {
protected function __construct() {}
public static function getInstance()
{
if (!isset($_SESSION['proposal'])) {
$_SESSION['proposal'] = new Proposal;
}
return $_SESSION['proposal'];
}
}

PHP - arrays in session variables

I have a problem with storing arrays in php session variables.
Let's say I have a session variable, and I assign to it array of objects.
$_SESSION['xxx'] = [new Obj(data[0], data[1]), new Obj(data[0], data[1])];
When I print the contents of $_SESSION['xxx'] after that, I get correct results. But when I follow a link to other page and try to read content of $_SESSION['xxx'] there, I get sth like that:
array('0'=>array('0'=> NULL, '1'=> NULL), '1'=>array('0'=> NULL, '1'=> NULL) )
Do you have an idea what can be a reason of that? For sure it is the same session.
Regards
Michal
Update
code of class:
class Bsk_pps {
public $id; //bsk_id
public $name; //bsk_name
public $code; //bsk_code
public $type;
public $count; //count of PROPERTIES elements assigned to this BUSINESS KEY
public function __construct($id, $name, $code, $type, $count) {
$this->id = $id;
$this->name = $name;
$this->code = $code;
$this->type = $type;
$this->count = $count;
}
}

Categories