Page 1 of 1

problem with class properties not holding their value

Posted: Tue May 29, 2007 8:30 am
by RestoSpeed
I'm stuck on this one, and I don't know why, maybe it has something to do with PHP 5 (I've written for 4 before).

when I create an object and set the value of a particular class property, it changes all the properties. I'm sure it's something simple, but I just don't get it.

Code: Select all

//---CREATE PROJECT-------
    class pObject{
      var $name;
      var $start_date;
      var $summary;
    }
      
    $test_pro = new pObject;                  //---- create the object
    $test_pro->$name = "test name";    //----- set the project name property
    echo $test_pro->$name;                   //----- returns "test-name"
    $test_pro->$start_date = "date";     //----- set the project start date property
    echo $test_pro->$start_date;           //----- returns "date"
    echo $test_pro->$name;                   //----PROBLEM also returns "date"
    echo $test_pro->$summary;             //----PROBLEM 2 this also returns "date" (as upposed to NULL)
thanks in advance.
-Brandon

Posted: Tue May 29, 2007 8:35 am
by feyd
$foo->$bar should be $foo->bar.

Also, "var" is deprecated. It should be "public" in this case.

Posted: Tue May 29, 2007 8:36 am
by vigge89
ditch the dollar signs after ->, otherwise strange things can happen:

Code: Select all

class testclass {
var $var;
}
$var = 'hello';
$object = new testclass;
echo $object->$var; // tries to echo $object->hello, but fails since no such variable exists
// correct usage:
$object->var = 'object var';
echo $object->var; // outputs 'object var'

Posted: Tue May 29, 2007 8:37 am
by superdezign
... I'm not sure, but probably because that's not technically a class, it's more of a structure (I learned OO as a C++ programmer so.. bare with me).

Structure's are function-less. I'm not sure hoe PHP handles them. Try giving it a default constructor.

Code: Select all

class pObject{
      var $name;
      var $start_date;
      var $summary;
      
      function __construct(){}
    }
And declare the object using that.

Code: Select all

$test_pro = new pObject();

Edit: Never mind. I was too slow. And blind. :-p

Posted: Tue May 29, 2007 8:41 am
by Kieran Huggins
lol - 3 replies in 3 minutes!

We're nothing if not thorough, RestoSpeed!

Posted: Tue May 29, 2007 8:56 am
by RestoSpeed
Thanks guys, it was the dollar signs after the "->" I knew it was something simple. Anywhoo, as far as being a class, it will have functions, but I thought better than to post the whole def.

-Brandon

Posted: Tue May 29, 2007 9:03 am
by superdezign
RestoSpeed wrote:Thanks guys, it was the dollar signs after the "->" I knew it was something simple. Anywhoo, as far as being a class, it will have functions, but I thought better than to post the whole def.

-Brandon
Good job. :-p
Personally, I hate to see long snippets.