Reputation: 368
Is it possible in PHP to, get a variable from another PHP file and assign it directly to a variable?
Eg. -
File 1 - users.php
<?php
[
"name" => "John",
"age" => 34
]
?>
File 2 - accounts.php
<?php
$user = get_var_from_file(users.php);
?>
get_var_from_file is the function that takes the array from users.php and assigns it directly and assigns it to $users
.
My goal here is to make the users.php file as simple as possible, because it's going to be accessed by non technical people.
Upvotes: 1
Views: 96
Reputation: 78994
I would use the JSON approach, failing that I would use the CSV approach, failing that maybe parse_ini_file. However, to answer the specific format you show, just eval
it:
function get_var_from_file($file) {
$array = file_get_contents($file);
eval("\$result = $array;");
return $result;
}
JSON is easy, so is the INI and the CSV can be easy:
$result = array_map('str_getcsv', file($file, FILE_IGNORE_NEW_LINES));
Upvotes: 0
Reputation: 34406
Make the file a JSON file (remove the PHP tags) and then use file_get_contents(user.json)
and then parse the JSON with json_decode()
. There will be no need to reassign to other variables, just use the array identifiers from the decoding process.
Upvotes: 1
Reputation: 14738
You can do it by require
keyword
file users.php
$users = [
'name' => 'John',
'age' => 34
];
file accounts.php
require('users.php');
$age = $users['age'];
echo $age;
// should return 34
Upvotes: 0
Reputation: 2744
simply return the variable you want to return :
<?php
return [
"name" => "John",
"age" => 34
]
?>
and in another file:
$users = include 'users.php';
Upvotes: 0