在PHP中,属性是用于存储对象状态的数据成员。它们可以是公共的(public)、受保护的(protected)或私有的(private),以便实现封装和数据隐藏。以下是一些关于PHP属性最佳实践和应用案例:
class Person {
private $name;
private $age;
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
public function getName() {
return $this->name;
}
public function getAge() {
return $this->age;
}
public function setName($name) {
if ($this->isNameValid($name)) {
$this->name = $name;
} else {
throw new InvalidArgumentException("Invalid name");
}
}
public function setAge($age) {
if ($this->isAgeValid($age)) {
$this->age = $age;
} else {
throw new InvalidArgumentException("Invalid age");
}
}
private function isNameValid($name) {
return strlen($name) > 0;
}
private function isAgeValid($age) {
return $age >= 0 && $age <= 150;
}
}
class Person {
protected $name;
protected $age;
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
public function getName() {
return $this->name;
}
public function getAge() {
return $this->age;
}
public function setName($name) {
if ($this->isNameValid($name)) {
$this->name = $name;
} else {
throw new InvalidArgumentException("Invalid name");
}
}
public function setAge($age) {
if ($this->isAgeValid($age)) {
$this->age = $age;
} else {
throw new InvalidArgumentException("Invalid age");
}
}
private function isNameValid($name) {
return strlen($name) > 0;
}
private function isAgeValid($age) {
return $age >= 0 && $age <= 150;
}
}
class Employee extends Person {
public function __construct($name, $age, $jobTitle) {
parent::__construct($name, $age);
$this->jobTitle = $jobTitle;
}
public function getJobTitle() {
return $this->jobTitle;
}
}
class Config {
const API_KEY = "your_api_key";
const API_URL = "https://api.example.com";
}
$config = new Config();
echo Config::API_KEY; // 输出 "your_api_key"
echo Config::API_URL; // 输出 "https://api.example.com"
class Database {
private static $instance;
private $connection;
private function __construct() {
$this->connection = new PDO("mysql:host=localhost;dbname=mydb", "username", "password");
}
public static function getInstance() {
if (self::$instance === null) {
self::$instance = new Database();
}
return self::$instance;
}
public function getConnection() {
return $this->connection;
}
}
$db = Database::getInstance();
$stmt = $db->getConnection()->prepare("SELECT * FROM users");
$stmt->execute();