1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
|
<?php
/* Boolean */ function save_var ($arg_f,$arg_var) // replace if value already set
{
if(!file_put_contents($arg_f,"<?php \nreturn ".var_export($arg_var,true)."\n?>",LOCK_EX))return false;
return true;
}
/* mixed */ function load_var($arg_f) // accept some default values, return false if problem, NULL if (filenotexist && any value found)
{
if(file_exists($arg_f)) return require($arg_f);
}
// initialisation (lisibilité)
$path_array=dirname(__FILE__).DIRECTORY_SEPARATOR.'path_array.php';
$path_var=dirname(__FILE__).DIRECTORY_SEPARATOR.'path_var.php';
$path_objectB=dirname(__FILE__).DIRECTORY_SEPARATOR.'path_objectB.php';
$path_objectC=dirname(__FILE__).DIRECTORY_SEPARATOR.'path_objectC.php';
// Exemple #1 Exemple avec var_export()
$a = array (1, 2, array ("a", "b", "c"));
save_var($path_array,$a);
unset($a);
$a=load_var($path_array);
var_export($a);
echo "\n";
$b = 3.1;
save_var($path_var,$b);
unset($b);
$b=load_var($path_var);
var_export($b);
echo "\n";
//Exemple #2 Exporter des classes depuis PHP 5.1.0
/*
class A { public $var; }
$a = new A;
$a->var = 5;
save_var($path_object,$a);
unset($a);
$a=load_var($path_object);
var_export($a);
echo "\n";
*/
//Exemple #3 Utilisation de __set_state (depuis PHP 5.1.0)
class B
{
public $var1;
public $var2;
public static function __set_state($an_array)
{
$obj = new B;
$obj->var1 = $an_array['var1'];
$obj->var2 = $an_array['var2'];
return $obj;
}
}
$b = new B;
$b->var1 = 5;
$b->var2 = 'foo';
save_var($path_objectB,$b);
unset($b);
$b=load_var($path_objectB);
var_export($b);
echo "\n";
// Exemple 4 : Juste un constructeur de plus
class C
{
public $var1;
public $var2;
function __construct($arg_var1,$arg_var2)
{
$this->var1 = $arg_var1;
$this->var2 = $arg_var2;
}
public static function __set_state($an_array)
{
$obj = new C;
$obj->var1 = $an_array['var1'];
$obj->var2 = $an_array['var2'];
return $obj;
}
}
$c = new C("chaine_1","chaine2");
save_var($path_objectC,$c);
unset($c);
$c=load_var($path_objectC);
var_export($c);
echo "\n";
echo $c->var1;
?> |
Partager