I've got two classes, and currently I reference one from the other by using this:
ClassB::func()
{
global $classAObject;
echo $classAObject->whatever();
}
However, I've been told that using global is discouraged. Is it, and why?
I've got two classes, and currently I reference one from the other by using this:
ClassB::func()
{
global $classAObject;
echo $classAObject->whatever();
}
However, I've been told that using global is discouraged. Is it, and why?
There are many reasons not to use globals. Here's just a few:
A better way to handle the example you gave in your post would be to pass the object containing the data you need.
classB::func($obj)
{
echo $obj->whatever();
}
$obj = new classAObject;
classB::func($obj);
The reason is that it flubs the idea of OOP encapsulation. It's much better to do:
ClassB::func($classAObject)
{
echo $classAObject->whatever();
}