[PHP]向类中动态添加数据

__set()方法可以向类中动态添加不存在的属性:


类定义:

class User{
	public $username;
	public $password;
	public $email;
	
	public function __set($name, $value) 
       {
        echo "Setting '$name' to '$value'\n";
        $this->$name = $value;
       }

调用:

<?php

require_once './User.class.php';

$user=new User();

$user->notExists='Can I Exists?Yes!I made it!';

var_dump($user);

运行结果:

Setting 'notExists' to 'Can I Exists?Yes!I made it!'
object(User)[1]
  public 'username' => null
  public 'password' => null
  public 'email' => null
  public 'notExists' => string 'Can I Exists?Yes!I made it!' (length=27)

你可能感兴趣的:([PHP]向类中动态添加数据)