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;
}
}
Related
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();
I'm sorry if the title was confusing or poorly worded, I'm relatively new to programming terminology and couldn't think of a better description.
Here is a basic structure of the script, with irrelevant functions/variables removed:
class User {
public $username;
public $binders;
function __construct($username, $binders) {
$this->username = $username;
$this->binders = $binders;
}
}
The variable $binders is an array of Binder objects:
class Binder {
public $name;
public $contents;
function __construct($name, $contents = array()) {
$this->name = $name;
$this->contents = $contents;
}
}
The variable $contents is an array of Card objects:
class Card {
public $id;
public $quantity;
function __construct($id, $quantity = 0) {
$this->id = $id;
$this->quantity = $quantity;
}
}
So a simple structure could be:
$users = array(
'TestName' => new User('TestName', array(
'BinderName1' => new Binder('BinderName1', array(
'CardID_1' => new Card('1', '20'),
'CardID_3' => new Card('3', '10'),
),
'BinderName2' => new Binder('BinderName2', array(
'CardID_1' => new Card('1', '7')
)
)
);
I'm currently attempting to update the quantity of the card with id of 1 in the binder BinderName1, using the following code:
$users['TestName']->binders['BinderName1']->contents['CardID_1']->quantity = 5;
However, when I use print_r($users) after applying the change, the response shows that the quantity of CardID_1 updates in both BinderName1 and BinderName2. Am I applying the change incorrectly?
Edit: it appears as though this only occurs when I create a clone of an object, eg:
$card = $users['TestName']->binders['BinderName1']->contents['CardID_1'];
$cloneCard = clone $card;
array_push($users['TestName']->binders['BinderName1']->contents, $cloneCard);
I am trying to call a public variable used in a class in another class. I am able to call the variable but it returns a blank array.
Code that I am working on,
Class One:
class fruits {
public $ID = array();
private function getFruitID() {
$fruitID = array('1' , '2', '3' , '4' , '5' );
return $fruitID;
}
private function getFruitsName() {
$fruitName = array('apple' , 'orange' , 'kiwi' , 'grapes' , 'mango');
return $fruitName ;
}
public function getstock() {
$this->ID = getFruitID();
/* Prints the ID list here */
$this->name = getFruitsName();
/* This function renders to the template */
}
}
Class Two:
class TestPage{
public function displayFruits() {
require_once ('fruits.php');
$fruits = new fruits();
$data = $fruits->ID;
echo($data);
/* displays an empty array */
}
}
When I echo $data inside displayFruits() on TestPage, it prints a blank array and not the actual ids. I am stuck with getting the ids on TestPage class. I could use a return, but that way I would end with just one variable, and I have multiple variables inside that function. Any help would be much appreciated.
you are not contructing the array with anything ..
public $ID = array();
is blank... until you call getFruitID
you can add it into the constructor if you need.
constructors PHP
function __construct( ){
$this->getstock();
}
This means when you create your object new Fruit();
It will assign the array in its creation.
At the moment it is empty.
public $ID = array();
Add below to populate array
class TestPage{
public function displayFruits() {
require_once ('fruits.php');
$fruits = new fruits();
$fruits->getstock();
$data = $fruits->ID;
echo($data);
}
}
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
Let's assume there are three classes:
Sponsor{id[int], name[string], sponsoredProjects[array of Project objects]}
Project{id[int], name[string], desc[string], sponsors[array of Sponsor objects]}
School{id[int], name[string], projectsDone[array of Project objects}
I'm stuck between Sponsor's sponsoredProjects and Project's sponsors.
Theoretically, if I create a Project then I need to create the Sponsor for it too. If I create Sponsor then I need to create the Project for it too.
So, that would result in endless arrays of Project with Sponsor within them with Project within them with Sponsors within them and etc. Am I right? Same problem should apply to School too since they have array of Project which have array of Sponsor which have array of Project and so on.
If so then how should I avoid this flaw?
My goal is to create all these objects from returned multiple SQL results temporarily, which in turn I will send to JavaScript page.
final class Sponsor{
private $_id;
private $_name;
private $_projects;
public function __construct($id, $name, Project $projects){
$this->setSponsor($id, $name, $projects);
}
public function getId(){
return $this->_id;
}
public function getName(){
return $this->_name;
}
public function getProjects(){
return $this->_projects;
}
private function setId($id){
$this->_id = $id;
}
private function setName($name){
$this->_name = $name;
}
private function setProject(Project $projects){
$this->_projects = array();
foreach($projects as $val){
array_push($this->_projects, $val);
}
}
private function setSponsor($id, $name, Project $projects){
$this->setId($id);
$this->setName($name);
$this->setProjects($projects);
}
}
final class Project{
private $_id;
private $_name;
private $_desc;
private $_sponsors;
public function __construct($id, $name, $desc, Sponsor $sponsors){
$this->setProject($id, $name, $desc, $sponsors);
}
private function setId($id){
$this->_id = $id;
}
private function setName($name){
$this->_name = $name;
}
private function setDesc($desc){
$this->_desc = $desc;
}
private function setSponsors(Sponsor $sponsors){
$this->_sponsors = array();
foreach($sponsors as $obj){
$id = $obj->getId();
$name = $obj->getName();
$projects = $obj->getProjects();
array_push($this->_sponsors, new Sponsor($id, $name, Project $this));
}
}
private function setProject($id, $name, $desc, Sponsor $sponsors){
$this->setId($id);
$this->setName($name);
$this->setDesc($desc);
$this->setSponsors($sponsors);
}
}
final class School{
private $_id;
private $_name;
private $_projectsDone;
public function __construct($id, $name, Project $projects){
$this->setSchool($id, $name, $projects);
}
private function setId($id){
$this->_id = $id;
}
private function setName($name){
$this->_name = $name;
}
private function setProjectsDone($projects){
$this->_projectsDone = array();
foreach($projectsDone as $val){
$this->{_projectsDone}[] = $val;
}
}
public function setSchool($id, $name, $projectsDone){
$this->setId($id);
$this->setName($name);
$this->setProjectsDone($projectsDone);
}
}
You've got a circular reference problem. Instead of each object holding an array of the objects it's related to, try keeping arrays of their ids and look up the related entity when you need it.
There's nothing wrong with having objects hold reference back and forth between each other. It's very common, and its a normal(reflexive) relation on a set. For example, the DOM in javascript...an Element node knows its children, and its children know their parent.
Obviously you need to take care when constructing and initializing them, as there's a little bit of a chicken & egg issue, but the check just boils down to
if relation to object not established
establish()
You mentioned you store this info in a database. You can probably even avoid the check. You probably have, for example, the following tables:
Sponsor
Project
School
SponsoredProjects - many to many relation
SchoolProjectsDone - many to many relation
Construct the Sponsor, Project, and School objects, and then loop over the relations in the SponsoredProjects and SchoolProjectsDone tables, associating the objects.