Home  >  Q&A  >  body text

内部类 - php中如何给类注册属性?

class a{

//主要功能是连接数据库,取出表中字段,将字段定义为子类属性,想以这种方式实现ActiveRecord
    function doQuery($dbname, $table){
        $fields = mysql_list_fields($dbname, $table);
        $num = mysql_num_fields($fields);
        $keys = array();
        for($i=0; $i<$num; $i++){
             array_push($keys, mysql_fields_name($fields);
        }
        return $keys;
     }
}

class b{
     function bind($data){
         foreach($data as $key=>$value){
             $this->$value = null;
         }
         print_r(get_class_vars(get_class($this));
     }
}

这样却无法输出 类b的属性

PHP中文网PHP中文网2748 days ago410

reply all(2)I'll reply

  • 阿神

    阿神2017-04-10 14:24:55

    get_class_vars — Get the default properties of the class

    动态定义的属性是不会被这个函数打出来的 ...

    如果你需要列出一个类的所有属性 ... 一段小技巧可以帮助到你 ...

    <?php
    class b {
    
        public function bind( $data ) {
    
            foreach ( $data as $key => $value )
                $this->$value = null;
    
            /* just make an array to output like you want ... */
            $ret = [];
    
            /* no need to do type conversion here ... php will done for us ... */
            foreach( $this as $key => $null_of_course )
                $ret[] = $key;
    
            /* miracle time ... */
            print_r( $ret );
    
        }
    
    }
    
    (new b)->bind( [ 
        'aa'    =>  'bb',
        'cc'    =>  'dd'
        ] );

    或者更简单的写法 ... 需要手动转化一下类型 ...

     $ret = array_keys( (array) $this ); 

    By the way ... 编辑一句题外话 ... tabsize 设成 5 的习惯是哪里来的 ..?

    reply
    0
  • 迷茫

    迷茫2017-04-10 14:24:55

    public function doQuery($table){
    			$fields = mysql_list_fields($this->dbName, $table);
    
    			$keys = array();
    			$num = mysql_num_fields($fields);
    
    			for ($i=0; $i < $num; $i++) { 
    				array_push($keys, mysql_field_name($fields, $i));
    			}
    
    			foreach ($keys as $key => $value) {
    				$this->$value = $value;
    			}
    
    			print_r($keys);
    			Echo '<pre>';
    			print_r(get_class_vars(get_class($this)));
    
    		}

    已经可以打印出来了,也注册上了;
    非常感谢

    reply
    0
  • Cancelreply