PDA

View Full Version : $variable-->stuff as $var



DouglasAWh
November 21st, 2007, 08:01 PM
I've got the syntax


foreach ($rss->items as $item)


in an example at which I am looking, but I am not familiar with the $variables-->stuff syntax. "items" is a variable in an include file in the example. Can someone tell me what is going on here?

Thanks!

aks44
November 21st, 2007, 08:14 PM
In PHP -> is used to access an object's member. In this case, $rss is the object, and it has (at least) a member variable named items.
$rss->items should be an array since you use foreach on it.

You'd better read about PHP classes and objects, perhaps find a tutorial about that on Google? If you already have some OOP experience it will give you a good headstart, and if you don't have such experience a tutorial will probably explain it better than I could.


As a side note, just a little advice: next time you post a question please specify which language is concerned. It may not always be obvious... ;)

smartbei
November 21st, 2007, 08:21 PM
$items is an array - that is important. What the foreach loop does is iterate through the array, each time assigning a value (in order) to $item, and then executing the loop body.
For example, the following code:


$arr = array("apple", "orange", "tomato");
foreach($arr as $val)
{
echo $val . "\n";
}

Would output:


apple
orange
tomato

The -> means that items is a member of a class, which $rss is an instance of. That is just the php syntax for accessing a class member variable.

Ther is also another variant of the foreach, which also gives you access to the keys holding the values:


$arr = array("apple","orange","tomato",25=>"pea");
foreach ($arr as $key => $val)
{
echo $key, " => ", $val;
}

Would output:


0 => apple
1 => orange
2 => tomato
25 => pea


Hope that cleared things up!

EDIT: Re-reading your post, I hope that you actually asked about the foreach as well (besides the ->) :D. If not, aks44 beat me to it :).

LaRoza
November 21st, 2007, 10:57 PM
In case you study other langauges, specifically C or C++, access to member data of objects and structures is done with a period, and the "->" is a shorthand for dereferencing a pointer.

Many languages use a "." to access member data.

DouglasAWh
November 22nd, 2007, 04:56 PM
thanks for the help! This hasn't, as of yet, helped me clear up the problem though. I'm pulling in an RSS feed and breaking it up using Magpie. I have one RSS 2.0 feed that works (http://www.trilug.org/node/feed) and one RSS 2.0 feed that does not work (http://ibiblio.org/snkahn/collectionsrss.php). Obviously, the second feed is PHP generated, but Firefox treats it as an RSS feed. One difference between the two feeds is that the TriLUG feed does not get colorized by Firefox, while the ibiblio feed does, so I don't know if that helps anyone. The TriLUG feed is generated by Wordpress. I'll post more if I figure something out.

Thanks again!