Reputation:
I am a newbie in PHP and I am asking wether I can initialize once for all data inside an object and use them later
<?
class Person(){
private $data;//private or public
function Person($data){
$this->data['name'] = $data['name'];
....
}
function save(){
$this->dbconn.executeQuery('insert into ... values('$this->data['name']',...));
//some object to connect and execute query on a database.
}
}
?>
$me = new Person(array(['name']=>'my fname my lname',...));
$me->save();
//print_r($me) shows that $data has no initialized values
How can I solve that problem. If you know a link where the same problem has been asked, please copy and paste it here. thank you.
Upvotes: 0
Views: 786
Reputation: 573
Two things. I think you're passing data incorrectly, as well as setting your class wrong:
<?php
class Person {
function __construct($data){
$this->data = array();
$this->data['name'] = $data['name'];
}
function save(){
// Do something here.
}
}
$info = array();
$info['name'] = "Joe Blogs";
$someone = new Person($info);
print_r($someone);
?>
For me, this prints out the information as it should.
Upvotes: 1
Reputation: 7956
you can use serialize and then store the object where you want. but in this case in particular you probably will have problems if you try to use the db connection after you unserialize the object since the connection for that object isn't persistent.
In the other hand remember to have always loaded the class definition if not when you try to unserialize the object you will get an error because php wont know the class you had serialized
Upvotes: 0