Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Array contents in classes

Status
Not open for further replies.

Keiser

Programmer
Joined
Jan 4, 2004
Messages
2
Location
US
Hi I'm currently programming what will eventually be a fully automated site for a computer gaming league, and I was having a problem with taking an array in and assigning it as a variable in a class. I'm a past C++ programmer, and I really havn't used PHP *that* much, so I'm just wondering if there's a quirky language problem I don't know about. I'm so against stealing scripts I won't even take a news system without knowing exactly what happens.

class newspost
{
var $poster;
var $timestamp;
var $title;
var $content=array(null);

function set($poster, $timestamp, $title, $content)
//This function sets this newspost to the input values
{
$this->poster=$poster;
$this->timestamp=$timestamp;
$this->title=$title;
$this->content=$content;
//for ($i=0;$i<count($content);$i++)
//$this->content[$i]=$content[$i];
echo &quot;$content[0]&quot;;
echo &quot;$this->content[0]&quot;;
}
//... couple more functions
}

Basically what happens is the array inside the class ($this->content) isn't set to what the input array is ($content). I've tried multiple ways of assigning it, including array_slice and that 'for' loop, but they all do the same thing, which is nothing. The first test echo outputs the correct value, but the second one just puts: Array[0]

Also, &quot;var $content=array(null);&quot; is only like that because I was testing if an array had to be declared as an array in the class. Neither that nor &quot;var $content;&quot; work.
 
Let's talk about the problem with the variable declaration in the class.

var $foo=<anything>;

won't work. PHP does not allow for initialization of a variable in the var statement. You'll have to use the class constructor for that.

But, you don't have to declare the variable as an array.


Another thing is printing variables inside quotes. If all you're printing is the variable, don't put the variable in quotes -- PHP can get confused inside quotes as to what you want. Don't ever put associative array references inside quotes -- they rarely work.

Try:

echo $content[0];
echo $this->content[0];

Want the best answers? Ask the best questions: TANSTAAFL!!
 
Hey thanks! I actually fixed it last night and figured that out just before going to bed. In my test script I was actually echo-ing with quotes and array references, just like you said. Annoying language quirk, just like I thought :And thanks for clearing it up about the var initialization in objects, it's good to know that.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top