How to write a Class object to a file?

Discussion in 'PHP' started by lukog, Mar 16, 2011.

  1. #1
    I wish to write an entire class to a txt file on the server...
    My class is as follows..
    <?php
    class userdata {
    var $username;
    var $password;
    }

    I wish to write this class to a text file. im given to understand that simply using the fwrite() function will not work. Is there any kind of function to write entire class objects to files? Plz help. Thanks!
     
    lukog, Mar 16, 2011 IP
  2. Minimal Hank

    Minimal Hank Peon

    Messages:
    136
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #2
    And I don't understand why couldn't you use fwrite(). Have you at least tried it ?
     
    Minimal Hank, Mar 16, 2011 IP
  3. BobbySteel

    BobbySteel Peon

    Messages:
    27
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    In the class itself, create a function called writeout or whatever and pass it the parameters of the file you want.

    public function writeout($outfile){
    // format parameters however
    fwrite($parameters,$outfile,w);
    }

    Then in the code, use Object.writeout($filename).
     
    BobbySteel, Mar 16, 2011 IP
  4. BobbySteel

    BobbySteel Peon

    Messages:
    27
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    You'll have to of course figure out how you want the object contents written out. Plaintext, csv, etc.
     
    BobbySteel, Mar 16, 2011 IP
  5. dgreenhouse

    dgreenhouse Peon

    Messages:
    24
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #5
    I'm not sure what your purpose is, but you can serialize objects in PHP.

    See: http://www.devshed.com/c/a/PHP/The-Basics-of-Serializing-Objects-in-PHP/
     
    dgreenhouse, Mar 16, 2011 IP
  6. Vooler

    Vooler Well-Known Member

    Messages:
    1,146
    Likes Received:
    64
    Best Answers:
    4
    Trophy Points:
    150
    #6
    <?php
    
    class userdata 
    {
      var $username;
      var $password;
    }
    
    $u  =new userdata;
    
    #saving
    file_put_contents('data.txt', serialize($u));
    
    
    #reading back and formign same type
    $u2 = unserialize(file_get_contents('data.txt'));
    
    
    Code (markup):

    Hope it helps.
     
    Vooler, Mar 17, 2011 IP