Helpful Information
 
 
Category: Coding tips & tutorials threads
PHP Tut: Objects within Classes

Not many people know or use this outstanding feature in their OOP scripts. Objects are a great way to contain organized information, for instance If I had a class called user, I may use some call like $user->name. This is normally not the case, as user functions are too specific for general site usage, so most use arrays to take care of this, like $database->user['name'] however this could easily be changed to $database->user->name. Instead of nesting classes (which can be messy) we can just use the object method to simplify everything. For Example:


class AnObjectWithinClass {
public $obj;
public function __construct()
{
$this->obj = (object) array('foo' => 'bar', 'property' => 'value');
}

}
$class = new AnObjectWithinClass;

You can now use a call like:


echo $class->obj->foo;//outputs bar
You can set them as well, just like properties:


$class->obj->foo = " lol";
echo $class->obj->foo;//outputs lol
You can use functions with them too!


//inside AnObjectWithinClass class
public function setObj($var, $value)
{
$this->obj->$var=$value;
}

Example function usage:


$class->setObj("foo"," test123");
echo $class->obj->foo;//outputs test123

$class->setObj("newvalue"," yay im new!");
echo $class->obj->newvalue;//outputs yay im new!
So all together:


<?
class AnObjectWithinClass {
public $obj;
public function __construct()
{
$this->obj = (object) array('foo' => 'bar', 'property' => 'value');
}
public function setObj($var, $value)
{
$this->obj->$var=$value;
}
}
$class = new AnObjectWithinClass;

echo $class->obj->foo;//outputs bar

$class->obj->foo = " lol";
echo $class->obj->foo;//outputs lol

$class->setObj("foo"," test123");
echo $class->obj->foo;//outputs test123

$class->setObj("newvalue"," yay im new!");
echo $class->obj->newvalue;//outputs yay im new!
?>

And that's pretty much the basis of using objects inside classes! :)










privacy (GDPR)