views:

194

answers:

2

Hi, 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.

A: 

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

Gabriel Sosa
+1  A: 

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.

EvilChookie
Thanks I am going to try this out, It looks like something that might WORK. the problem might be the way I construct my objects. I used PHP4 way for initialization. data initialization has no problem, as I used a notation only to be brief. thanks again for the response.
No problems - this should work, as I uploaded it to a test server and go the expected response. LMK if this helps.
EvilChookie
It works I tried this out =:class Tester{ function __construct($data){ $this->data = array(); $this->data['name'] = $data['name']; $this->data['age'] = $data['age']; } function save(){ echo 'called<br/>'; print_r($this); } } $me = new Tester(array("name"=>"Pascal Maniraho","age"=>2000)); $me->save();and I got calledTester Object ( [data] => Array ( [name] => Pascal Maniraho [age] => 2000 ) ) thanks for the help again.