Jump to content

Archived

This topic is now archived and is closed to further replies.

cCj

How to save the array vars in a class?

Recommended Posts

Hi,
I'm using serialize to save an object which worked until I started using Arrays in the class. Please see this code below:

[code]class Base extends Tile
{
var $owner;
var $resources = Array();

function Base($owner)
{
$this->Tile();
$this->owner = $owner;
}
function __sleep()
{
  // used this before which works for simple vars like owner
    //return array('owner');
  // trying this now but doesn't seem to work for arrays
return( array_keys( get_object_vars( &$this ) ) );
}
}[/code]

Then you would just call serialize and unserialize.

But like I commented that doesn't work, the array is not saved.
Any suggestions what could I try?

Thanks.

Share this post


Link to post
Share on other sites
What do you mean with "the array is not saved"?

Share this post


Link to post
Share on other sites
[quote author=poirot link=topic=103711.msg413179#msg413179 date=1155216728]
What do you mean with "the array is not saved"?
[/quote]

It's empty once unserialized. The owner var however has it's value so I was thinking that it was "not saved".

Share this post


Link to post
Share on other sites
I don't see any point in your __sleep() function.

If you run the script below it will create a Base object then save it. On subsequnt runs it pickes up the saved object (check the time values)

[code]<?php
session_start();


class Base
{
var $owner;
var $resources = Array();

function Base($owner)
{
$this->owner = $owner;
$this->resources = getdate();
}
}

if (isset($_SESSION['mybase'])) {
$obj = unserialize($_SESSION['mybase']) ;
} else {
$obj = new Base(1);
}

echo '<pre>', print_r($obj, true), '</pre>';

$_SESSION['mybase'] = serialize($obj);
?>[/code]

Share this post


Link to post
Share on other sites
Thank you Barand, your code works just like mine and I was able to find the problem now that I knew the problem was not in the serialazation.
What I was doing was something like this:

[code]
$tile = $map[$y][$x];
$tile->addToUnits($unit);
[/code]

When the working code was:
[code]
$map[$y][$x]->addToUnits($unit);
[/code]

So I had misunderstood how php handles variables, even $map had objects the assigment to $tile actually copied the object instead of passing reference to it. So I will be using & to get the reference instead of copy from now on.

Thanks.

Share this post


Link to post
Share on other sites
If you can, move to php5. Its object handling is far superior, and "by ref" is the default instead of passing copies of objects.

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.