Reputation: 4857
This is a very basic php question : suppose I have 3 files, file1, file2, file3.
In file1 I declare a class called Object. In file2, I have a method that instantiate Object, call it $object, and call this method Method
In file2, this method looks like
public function Method(){
$object = new Object;
...
require_once(file3);
$anotherobject = new AnotherObject;
$anotherobject->method();
}
Finally, in file 3 I declare another AnotherObject. So, if I have a method 'method' in file3, can I refer to $object's properties directly, or could I access ony the static method of Object ?
Upvotes: 2
Views: 7752
Reputation: 21856
This is not how decent OOp should be programmed. Give each class its own file. As I understand it you have 3 files with classes in them and want to use a the instantiated objects. Use Dependency Injection to construct classes that depend on each other.
Example:
file1.php:
class Object
{
public function SomeMethod()
{
// do stuff
}
}
file2.php, uses instantiated object:
class OtherObject
{
private $object;
public function __construct(Object $object)
{
$this->object = $object;
}
// now use any public method on object
public AMethod()
{
$this->object->SomeMethod();
}
}
file3.php, uses multiple instantiated objects:
class ComplexObject
{
private $object;
private $otherobject;
public function __construct(Object $object, OtherObject $otherobject)
{
$this->object = $object;
$this->otherobject = $otherobject;
}
}
Tie all this together in a bootstrap file or some kind of program file:
program.php:
// with no autoloader present:
include_once 'file1.php';
include_once 'file2.php';
include_once 'file3.php';
$object = new Object();
$otherobject = new OtherObject( $object );
$complexobject = new ComplexObject( $object, $otherobject );
Upvotes: 10
Reputation: 1918
the scope of $object
there is limited to the method of course. file 3 is called from the method, so I would think yes, if using include()
. using require_once()
from inside the method however, makes me ask other questions concerning the potential of file3 not being able to take advantage of the variables in the method shown if it is previously included elsewhere and therefore not included from within the method.
Upvotes: 1