Advanced PHP and objects help

So I’m a self taught php guy (like most of you I assume) and after tons of google searching I can’t find the answer to two questions, so any smart php guys out there can you help me out?

Question 1:
So I have a object, say like this
class MyObject
{
var Test1
var Test2
var Test3
}

And I refference this by going
ThisObject = New MyObject
ThisObject->Test1 = 1
ThisObject->Test2 = 2
ThisObject->Test3 = 3

is there any way to do this quickly, say with a for next loop?

Like:
While (x<=3)
{
ThisObject->Test[x] = x
}

???

Question 2:
Is there a way to loop through all available structure varables available publicly?

Like a Foreach(ThisObject ->Variables as ThisVar)
{
ThisIsTest1=ThisVar
//Next will be Test2
}

Or even a list of the local structure variables to see if something exists (or search for it) in code?

The first question is really important as I want to save a few lines of code in quite a few places, the structure I am pulling the data from isn’t of my creation, otherwise I would have put it into an array and returned it for such a reason as to save on code.

Thanks in advance

Question 1: So I have a object, say like this class MyObject { var Test1 var Test2 var Test3 }

And I refference this by going
ThisObject = New MyObject
ThisObject->Test1 = 1
ThisObject->Test2 = 2
ThisObject->Test3 = 3

is there any way to do this quickly, say with a for next loop?

Like:
While (x<=3)
{
ThisObject->Test[x] = x
}

Sure. You can do this…

<?php
$object = new MyObject();
for($x=1; $x<=3; $x++){
    $property = "Test" . $x;
    $object->$property = $x;
}
?>
Question 2: Is there a way to loop through all available structure varables available publicly?

Like a Foreach(ThisObject ->Variables as ThisVar)
{
ThisIsTest1=ThisVar
//Next will be Test2
}

Or even a list of the local structure variables to see if something exists (or search for it) in code?

PHP 5 allows object iteration…

// all visible properties will be used for the iteration
foreach($ThisObject as $key => $value){
    print "Property $key has the value $valuen";
}

Hope this helps.

ad

Sponsor our Newsletter | Privacy Policy | Terms of Service