Home >Backend Development >PHP Tutorial >PHP object-oriented classes and instantiated objects
This article mainly introduces PHP object-oriented classes and instantiated objects, which has a certain reference value. Now I share it with everyone. Friends in need can refer to it
Class
[修饰符] class 类名 { [属性] [方法] }
1) The class name follows the camel case naming convention that starts with uppercase
private 私有 protected 保护 public 公共 var 被视为public (不建议使用)
// 1.声明类 class Dog { // 2.定义属性 public $name = '旺财'; public $sex = null; // 3.定义方法 public function bark() { echo '汪汪~'; } } // 4.实例化 $d1 = new Dog();
Instantiated objectInvocation of properties and methodsUse
-> , to access non-static properties | methods.
Example
// 声明类 class Dog { // 定义属性 public $name = '旺财'; public $sex = null; // 定义方法 public function bark() { echo '汪汪~'; } } // 实例化 $d1 = new Dog(); // 使用属性和方法 echo $d1 -> name; echo '<br/>'; echo $d1 -> bark();Internal callWhen a method is called inside a class definition, you can use pseudo variables
$this .
$this represents the object being used.
Example:
// 声明类 class Dog { // 定义属性 public $name = '旺财'; public $sex = null; public function intruduce() { echo '我的名字是'.$this->name; } }Transfer assignment1)
Simple type, both sides of the assignment, mutually independent.
composite type, the identifier of the object is stored in the transfer assignment, so the changes are consistent .
Simple type example:
$a = 'abc'; // 传递赋值 $b = $a; // 更改a的值 $a = 'qq'; var_dump($a); // qq var_dump($b); // abc
Composite type example:
class MyClass { public $str = 'abc'; } // $a 存的是对象的标识符 $a = new MyClass(); // 传递赋值 相当于把标识符赋值给了$b $b = $a; var_dump($a); // abc var_dump($b); // abc // 更改a对象str属性的值 $a -> str ='111'; // $a和$b存的都是标识符 var_dump($a); // 111 var_dump($b); // 111 // 更改a本身的值 $a = 123; var_dump($a); // 123 var_dump($b); // 111 对象标识符Reference assignmentWhether it is Whether it is a simple type or a conforming type, both changes are consistent.
Example:
$a = 'abc'; // 引用赋值 $c = &$a; var_dump($a); // qq var_dump($c); // qqRelated recommendations:
php basic object-oriented concepts
The above is the detailed content of PHP object-oriented classes and instantiated objects. For more information, please follow other related articles on the PHP Chinese website!