Home > Back-end >  PHP Modify Variable
PHP Modify Variable

Time:01-03

There is a PHP file called test2.php,the code is in follow:

<?php
$data=array(
    'name' => 'jack',
    'age' => 8,
);
?>

I want to modify the $data in anoher php file called test1.php, but i find that if only use:

require_once "./test2.php";
$data['age']=10;
echo $data['age'];

Although the output is 10,but $data in test2.php dosen't change.

I want to know how to edit a PHP file in anoher PHP file.

CodePudding user response:

To change the contents of test2.php, you need to use a code editor (or... thru file_put_contents (make sure your file is writable), or use a database approach to store the data values, etc.)

However, if you just want to change the value of the age element of the $data array thru programming, then you can use session variables to do what you want

So change test2.php to

<?php
session_start();

if (!isset($_SESSION["data"])) {
   $_SESSION["data"]=array(
            'name' => 'jack',
            'age' => 8,
   );
}

echo $_SESSION["data"]["age"];


?>

and use the following as test1.php

<?php
session_start();

//require_once "./test2.php";
//$data['age']=10;
//echo $data['age'];

$_SESSION["data"]["age"]=10;

echo "Data changed, please visit test2.php to see the effect";

?>

Please try these steps:

  1. visit the test2.php and see the value of $_SESSION["data"]["age"] echoed
  2. visit the test1.php (to change the data)
  3. visit test2.php and see what happens

CodePudding user response:

You can do this by initialising your $data array as a global variable within your test2.php file.

  •  Tags:  
  • php
  • Related