Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use an instantiated object across different PHP files

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 ?

like image 260
user1611830 Avatar asked Dec 06 '25 09:12

user1611830


2 Answers

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 );
like image 193
JvdBerg Avatar answered Dec 08 '25 22:12

JvdBerg


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.

like image 29
NappingRabbit Avatar answered Dec 08 '25 21:12

NappingRabbit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!