Skip to content
PHP Logo

How can objects be passed between different PHP files?

To pass objects between different PHP files, you can use sessions or serialization. Sessions allow you to store objects in a session variable that can be accessed across different files, while serialization involves converting an object into a string that can be stored in a file or database and then retrieved and unserialized in another file.

php
// File 1: storing an object in a session variable
session_start();
$object = new MyClass();
$_SESSION['myObject'] = $object;

// File 2: retrieving the object from the session variable
session_start();
$object = $_SESSION['myObject'];
```

```php
// File 1: serializing an object and storing it in a file
$object = new MyClass();
file_put_contents('object.txt', serialize($object));

// File 2: retrieving and unserializing the object from the file
$object = unserialize(file_get_contents('object.txt'));