面向对象认识之类的转化

学习Java必不可少的要接触类,而在Java中类是特殊的存在,下面分享一下一些类的转化技巧。如果想了解更多编程语言教程知识请登录e良师益友网。
1、常量转变成常类型
常量实例:
define("LEVEL_ERROR",'error');
define("LEVEL_WARNING",'warning');
define("LEVEL_INFO",'info');
define("LEVEL_TRACE",'trace');
常类型实例:
class Level {
const ERROR = 'error';
const WARNING = 'warning';
const INFO = 'info';
const TRACE = 'trace';
}
2、变量转成属性
变量实例:
$userName = "张三";
$userAge = 18;
$userAddress = "xx省xx市xx镇xx村";
属性实例:
class User {
private $name;
private $age;
private $address;
/**
* @param mixed $address
*/
public function setAddress($address)
{
$this->address = $address;

}

/**
* @return mixed
*/
public function getAddress()
{
return $this->address;
}
/**
* @param mixed $age
*/
public function setAge($age)
{
$this->age = $age;
}
/**
* @return mixed
*/
public function getAge()
{
return $this->age;
}
/**
* @param mixed $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* @return mixed
*/
public function getName()
{
return $this->name;
}
public function __construct($name="",$age=0,$address=""){
$this->name = $name;
$this->age = $age;
$this->address = $address;
}
}
$user = new User("张三",18, "xx省xx市xx镇xx村");
3、静态变量转成静态属性
静态变量实例:
static $app;
if($app == null){
$app = new App();

}

静态属性实例:
class App {
private static $app = null;
public function instance(){
if(self::$app == null){
self::$app = new self;
}
return self::$app;
}
}
4、静态函数转成静态方法
静态函数实例:
function version(){
return "1.0.0.0";
}
静态方法实例:
class App {
public static function version(){
return "1.0.0.0";
}
}
5、全局变量转成属性
全局变量实例:
function login($password){
global $user;
if($user->password === $password){
return true;
}
throw new Exception("invalid password!");

}

属性实例:
class UserService {
private $user;
/**
* @param mixed $user
*/
public function setUser($user)
{
$this->user = $user;
}
 
/**
* @return mixed
*/
public function getUser()
{
return $this->user;
}
public function login($password){
if($this->getUser()->password == $password){
return true;
}
throw new Exception("invalid password!");
}
}
6、Map数组转成对象
Map数组实例:
$orderItems = array();
function addItem($product,$num,&$orderItems){
$orderItems[] = array("product"=>$product,"num"=>$num);
}
对象实例:
class Order {
private $items;
 
public function addItem($product,$num){
$this->items[] = new OrderItem($product,$num);

}

}

class OrderItem {
private $product;
private $num;
 
public function __construct($product,$num){
$this->product = $product;
$this->num = $num;
}
}
posted @ 2014-09-13 17:06  语过添情want  阅读(94)  评论(0编辑  收藏  举报