Home > Backend Development > PHP Tutorial > 内部类 - php中如何给类注册属性?

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

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-06 20:51:16
Original
1086 people have browsed it

class a{

//主要功能是连接数据库,取出表中字段,将字段定义为子类属性,想以这种方式实现ActiveRecord
    function doQuery($dbname, $table){
        $fields = mysql_list_fields($dbname, $table);
        $num = mysql_num_fields($fields);
        $keys = array();
        for($i=0; $i$value){
             $this->$value = null;
         }
         print_r(get_class_vars(get_class($this));
     }
}
Copy after login
Copy after login

这样却无法输出 类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$value){
             $this->$value = null;
         }
         print_r(get_class_vars(get_class($this));
     }
}
Copy after login
Copy after login

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

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'
    ] );
Copy after login

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

 $ret = array_keys( (array) $this ); 
Copy after login

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  $value) {
				$this->$value = $value;
			}

			print_r($keys);
			Echo '<pre class="brush:php;toolbar:false">';
			print_r(get_class_vars(get_class($this)));

		}
Copy after login

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

Related labels:
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
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template