<?php
/*
* PHP OOP
*
*/
//
//访问属性、方法用->符号,obj->Method()
//静态成员:self::Method()
//$this对象自己的引用,$this->Method()
//php
class Widget
{
private $_id = 0;
private $_name = '';
private $_description = '';
private static $s_StaticVar = 1;c#
public function __construct($widgetId) //构造函数
{
$this->_id = $widgetId;
echo 'Widget__construct';
}函数
public function getId() //惯例:自定义存取器
{
return $this->_id;
}this
public function setId($widgetId)
{
$this->_id = $widgetId;
}对象
public function getName()
{
return $this->_name;
}继承
public function setName($name)
{
$this->_name = $name;
}接口
public function getDescription()
{
return $this->_description;
}ip
public function setDescription($description)
{
$this->_description = $description;
}get
public function ParseHtml()
{
echo "Id:$this->_id, Name:$this->_name, Description:$this->_description, StaticTest:" .self::$s_StaticVar;
self::$s_StaticVar++; //访问静态成员又须要这个$了
}io
public function __destruct() //析构函数
{
echo "__destruct";
}
}
//
$test = new Widget(1);
$test->ParseHtml();
// $test2 = $test;
// $test2->ParseHtml();
$test3 = new Widget(1);
$test3->ParseHtml(); //类对象共享静态字段
/*
* 继承以后,构造函数、析构函数的调用顺序??
* 并不会自动调用父类构造函数,要子类本身调用
*
*/
class pageWidget extends Widget
{
public function __construct($widgetId, $name, $desc)
{
parent::__construct($widgetId);
echo 'pageWidget__construct';
parent::setName($name);
parent::setDescription($desc); //parent::访问父类,对应c#的base
}
public function __destruct() //属于重写了父类析构
{
parent::__destruct(); //只能子类主动调用了
}
public function ParseHtml() //重写父类方法
{
parent::ParseHtml();
echo "(我能呵呵一下吗)";
}
}
//
$pageWidget = new pageWidget(1, 'Hello', 'Hello world');
$pageWidget->ParseHtml();
//
//
/*
* 接口
* PHP不支持多继承,那能单继承类,实现多接口吗??对比C#
* 接口没有成员变量===和C#不一样
* 方法是abstract的
*/
interface IOpenable
{
function Open();
function Close();
}
interface IEnumerable
{
function GetEnumerator();
}
/*
* 继承一个类实现多个接口是能够的
* 这个子类没有自定义构造函数,可是,在实例化的时候,却能够利用父类的构造函数
* 看下面的注释
*/
class TestInterface extends Widget implements IOpenable, IEnumerable
{
public function Open() //如何显式说明属于IOpenable接口??==========
{
}
public function Close()
{
}
public function GetEnumerator()
{
}
}/* * 能够指定函数参数的类型 */function paramTypeTest(TestInterface $interface){ $interface->ParseHtml();}//paramTypeTest(new TestInterface(1)); //TestInterface自己没有这样的构造,可是能够这样利用父类的构造函数,汗...好自由////