Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> PHP

วิธีเก็บ config data ที่แก้ไขง่ายที่สุดใน PHP


Serialize ดีกว่า JSON สำหรับเก็บตัวแปร PHP

var_export ใช้บันทึก config file และ 'include' ใช้โหลดข้อมูล config file

เป็นวิธีง่ายๆ ในการบันทึก config data ด้วยโปรแกรม และอ่าน/เขียนง่าย โค้ดตัวอย่างด้านล่าง:

config.php

return array(    'var_1'=> 'value_1',    'var_2'=> 'value_2', );

test.php

$config = include 'config.php'; $config['var_2']= 'value_3'; file_put_contents('config.php', '<?php return ' . var_export($config, true) . ';');

แทน test.php ข้างต้น โค้ดด้านล่างก็ใช้ได้:

$config = include 'config.php'; $config['var_2']= 'value_3'; file_put_contents('config.php', '$config = ' . var_export($config));

config.php ที่อัปเดตแล้วมีโค้ดดังนี้:

return array(    'var_1'=> 'value_1',    'var_2'=> 'value_3', );