PHP的OOP

  • 在类中可以使用public(公有),protected(受保护)或 private(私有)来修饰属性和方法。如果不修饰默认是public。
  • 类中用var定义变量,var $name,使用方式$this->name
  • 构造函数function __construct(),析构函数function __destruct()
  • 继承class Child_Site extends Site,使用extends关键字
  • 实例化类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Login
{
var $m_user;
var $m_pw;

function __construct($user, $pw)
{
$this->m_user = $user;
$this->m_pw = $pw;
}

function Login()
{
echo $this->m_user .'-'. $this->m_user;
}
}

$user = $_POST['user'];
$pw = $_POST['pw'];

$login = new Login($user, $pw);
$login->Login();
  • 可以使用interface
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?php

// 声明一个'iTemplate'接口
interface iTemplate
{
public function setVariable($name, $var);
public function getHtml($template);
}


// 实现接口
class Template implements iTemplate
{
private $vars = array();

public function setVariable($name, $var)
{
$this->vars[$name] = $var;
}

public function getHtml($template)
{
foreach($this->vars as $name => $value) {
$template = str_replace('{' . $name . '}', $value, $template);
}

return $template;
}
}
  • 常量
1
2
3
4
5
6
7
8
9
10
11
<?php
class MyClass
{
const constant = '常量值';

function showConstant() {
echo self::constant . PHP_EOL;
}
}

echo MyClass::constant . PHP_EOL;
  • 静态属性不能通过一个类已实例化的对象来访问(但静态方法可以)。
  • 静态属性不可以由对象通过 -> 操作符来访问。调用方法是::
  • 抽象类与C#一样
  • Final 关键字,作用与C#的sealed一样。
  • 子类中调用父类的方法parent::Login();,与C#的base.Login结构上一样。
# PHP
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×