Can you define class variables from within a class method in PHP?
I want to pull all info about a file from a files table, but that table's structure might change.
So, I'd l开发者_开发百科ike to pull all the field names from the table and use them to generate the class variables that contain the information, then store the selected data to them.
Is this possible?
Yes you can, see php overloading.
http://php.net/manual/en/language.oop5.overloading.php
Quick Example: ( Not this isn't great usage )
<?php
class MyClass{
var $my_vars;
function __set($key,$value){
$this->my_vars[$key] = $value;
}
function __get($key){
return $this->my_vars[$key];
}
}
$x = new MyClass();
$x->test = 10;
echo $x->test;
?>
Sample
<?php
class TestClass
{
public $Property1;
public function Method1()
{
$this->Property1 = '1';
$this->Property2 = '2';
}
}
$t = new TestClass();
$t->Method1();
print( '<pre>' );
print_r( $t );
print( '</pre>' );
?>
Output
TestClass Object
(
[Property1] => 1
[Property2] => 2
)
As you can see, a property that wasn't defined was created just by assigning to it using a reference to $this
. So yes, you can define class variable from within a class method.
精彩评论