当前位置:Gxlcms > PHP教程 > 内部类-php中如何给类注册属性?

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

时间:2021-07-01 10:21:17 帮助过:16人阅读

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的属性

回复内容:

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的属性

get_class_vars — Get the default properties of the class

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

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

 $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 的习惯是哪里来的 ..?

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 '
';
			print_r(get_class_vars(get_class($this)));

		}

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

人气教程排行