本文主要是介绍php对象,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
<?php
//class基本语法-------------------------
class User {
//创建属性
public $username = 'ryu';
public $email = 'a@g.com';
//方法
public function addFriend() {
return "$this->email added a new friend";
}
}
//实例化对象
$userOne = new User();
$userTwo = new User();
$
//调用
echo $userOne->username . '<br>';
echo $userOne->email . '<br>';
echo $userOne->addFriend() . '<br>';
$userTwo->username = 'mj';
$userTwo->email = 'b@g.com';
echo $userTwo->username . '<br>';
echo $userTwo->email . '<br>';
echo $userTwo->addFriend() . '<br>';
//构造函数语法--------------------------
<?php
class User {
//定义变量
public $username;
public $email;
//private $email;私有只允许类方法内部使用
//构造函数
public function __construct($username, $email)
{
$this->username = $username;
$this->email = $email;
}
public function addFriend() {
return "$this->email added a new friend";
}
}
//传入参数
$userOne = new User('mario', 'mario@g.com');
$userTwo = new User('liye', 'liye@g.com');
echo $userOne->username . '<br>';
echo $userOne->email . '<br>';
echo $userOne->addFriend() . '<br>';
// $userTwo->username = 'mj';
// $userTwo->email = 'b@g.com';
echo $userTwo->username . '<br>';
echo $userTwo->email . '<br>';
echo $userTwo->addFriend() . '<br>';
//继承--------------------------------
<?php
class User {
//定义变量
public $username;
public $email;
//构造函数
public function __construct($username, $email)
{
$this->username = $username;
$this->email = $email;
}
public function addFriend() {
return "$this->email added a new friend";
}
}
//继承
class AdminUser extends User {
public $level;
//新加入level参数
public function __construct($username, $email, $level)
{
$this->level = $level;
//避免覆盖,重新导入父类构造函数,以及参数
parent::__construct($username, $email);
}
}
//传入参数
$userOne = new User('mario', 'mario@g.com');
$userTwo = new User('liye', 'liye@g.com');
$userThree = new AdminUser('chen', 'chen@g.com', 5);
//因为重新导入父类构造函数,参数,可以继续使用
echo $userOne->username . '<br>';
//新参数
echo $userThree->level;
//静态属性,不用实例化对象直接调用------------
<?php
//静态属性keyword(static)class可以直接调用,不用实例化对象
class Weather {
public static $tempConditions = ['cold', 'mild', 'warm'];
public static function celsiusToFarenheit($c){
return $c * 9 / 5 + 32;
}
public static function determineTempCondition($f){
if($f < 40){
return self::$tempConditions[0];//self::代表类本身
} elseif($f < 70){
return self::$tempConditions[1];
} else {
return self::$tempConditions[2];
}
}
}
//print_r(Weather::$tempConditions);
//直接调用class内属性,方法,没有实例化对象
echo Weather::celsiusToFarenheit(50) . '<br>';
echo Weather::determineTempCondition(80);
这篇关于php对象的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!