bunner bob;10925483 wrote:I'm not sure I understand how I'd use an object - well I do understand how to pass an object as a parameter, but don't I then need to create another class for the object that gets passed to the class? What would that look like - just a class that's a bunch of variables, no methods?
Yes, it could just be a "methodless" object. In that case it's not really much more than an array, other than that any class variables you define for it essentially guarantee that they'll exist (though not necessarily have any data), whereas all you know when you pass an array is that it's an array. (Well, actually, all you know is that it's a variable unless/until you check to see if it's an array.) In this example, we'll add a constructor that allows you to set the values initially, with the second being optional.
class Thingamajig
{
public $foo;
public $bar;
public function __construct($foo, $bar = null)
{
$this->foo = $foo;
$this->bar = $bar;
}
}
class Example
{
public function test(Thingamajig $thing)
{
echo $thing->foo . ' - ' . $thing->bar;
}
}
// USAGE:
$thingy = new Thingamajig("Value #1", "Value Two");
$obj = new Example();
$obj->test($thingy);
// More compact:
$obj = new Example();
$obj->test(new Thingamajig("Value #1", "Value Two");
Another variation would be to have a class variable in Example to hold a Thingamajig object, or it could even hold an array of Thingamajig objects if it makes sense for that class to have a collection of such objects. Then Example could have various methods that would all have access to the Thingamajig object(s).
class Example
{
private $thing;
public function __construct(Thingamajig $thing)
{
$this->thing = $thing;
}
public function test()
{
echo $this->foo . ' - ' . $this->bar;
}
}
// USAGE:
$obj = new Example(new Thingamajig("one", "two"));
$obj->test();