0

I have two files say file1.php and file2.php. I have one php file named form in which class form has been defined. I have created an object in file1.php as follow:

require_once('form.php');
$x=$_GET['field'];
$form = new Form("", ""); 
$personal = new Block("");

$address = new TextArea("address", $x, "", 3, 30); 
$personal->add($address);
$form->add($personal);
echo $form;

now i want to use this object $form and $personal in another file file2.php which is as follow:

$personal = new Block("");
$name = new Text("name",$x);
$personal->add($name);
$form->add($personal);
echo $form;

how can i use these objects in php. please help.

Rohitashv Singhal
  • 4,517
  • 13
  • 57
  • 105

3 Answers3

1

If you include one PHP file into the other, there is no problem, as the code in both will get merged to the scope of the including code.

Otherwise, if you wish to us re-use the objects at different positions in your code, you can use a registry (see also: How is testing the registry pattern or singleton hard in PHP?) to store the instantiated object.

If you plan to re-use the same objects on the next page load you need to serialize them, store the serialized object in the session/cache (or elsewhere) and unserialize it after loading the next page. In that case you'll also need some mechanism to set up a database connection or perform other required tasks (see: __wakeup()).

Community
  • 1
  • 1
feeela
  • 29,399
  • 7
  • 59
  • 71
0

Usually, you'll have to make a new instance of the object for each time a script is run.

If not, you could serialize the object, which puts it into a string format, then unserialize it when you need it, but you'll have to store the string somewhere. It's usually easier just to declare a new class.


In most cases like this, you'll use your object to modify values in a database. When the new instance is created (on page reload), it looks at the database to get the modified values. This way, the same instance doesn't have to persist across reloads.

Your class would use getters and setters ("accessors" and "modifiers") to work with the values you need - $address, for example.

Ben
  • 54,723
  • 49
  • 178
  • 224
0

first include file1.php

then just call the instances:

require_once('file1.php');
$name = new Text("name",$x);
$personal->add($name);
$form->add($personal);
echo $form;

keeping in mind that the instances of $form and $personal are already created in file1.php

FLY
  • 2,379
  • 5
  • 29
  • 40