Home > Backend Development > PHP Tutorial > php dynamically create attributes

php dynamically create attributes

巴扎黑
Release: 2016-11-12 10:49:29
Original
2208 people have browsed it

I just learned that php can dynamically create attributes, just like javascript.

Php code

class Book{  
        public $name;  
        public function __construct($name) {  
                $var=  func_get_arg(0);  
                if(is_int($var)){  
                        $this->name="12345".$name;  
                }  
                if(is_string($name)){  
                          $this->name=$name;  
                }  
                
        }  
          
}  
  
class Main{  
          
        public static  function createbook($class,$config=null){  
                return new $class($config);  
        }  
        public function config($config){  
                if(is_array($config)){  
                        foreach($config  as $key=>$val){  
                                $this->$key=$val;  
                        }  
                }  
        }  
}  
$config=array(  
                         'name'=>'My Web Application',  
);  
$main=new Main();  
$main->config($config);  
  echo  $main->name;
Copy after login

The result will output "My Web Application";

And the overloading of php is achieved through func_get_arg(0), func_num_args() .


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template