在这一节中,我们就来看看在PHP中如何创建一个类和对象。
1. 创建类
在PHP中,创建一个类和在C#/Java中基本类似,闲话少说,给大家看个最简单的例子:
复制代码 代码如下:
class People
{
var $name;
public function GetName()
{
return $this->name;
}
public function SetName($name)
{
$this->name=$name;
}
}
$p=new People();
$p->SetName("kym");
echo($p->GetName());
?>
复制代码 代码如下:
class People
{
private $name;
public function GetName()
{
return $this->name;
}
public function SetName($name)
{
$this->name=$name;
}
}
复制代码 代码如下:
class People
{
private $name;
public function GetName()
{
return $this->name;
}
public function SetName($name)
{
$this->name=$name;
}
}
$p=new People();
$get="GetName";
$set="SetName";
$p->$set("kym");
echo($p->$get());
?>
复制代码 代码如下:
class DataBase
{
public static function CreateConnection()
{
echo("Success");
}
}
DataBase::CreateConnection();
?>
复制代码 代码如下:
class DataBase
{
static $connectionString="http://127.0.0.1";
public static function CreateConnection()
{
echo("Success");
}
}
echo(DataBase::$connectionString);
DataBase::CreateConnection();
?>
复制代码 代码如下:
class DataBase
{
const AUTHOR="kym";
static $connectionString="http://127.0.0.1";
public static function CreateConnection()
{
echo("Success");
}
}
echo(DataBase::AUTHOR);
echo(DataBase::$connectionString);
DataBase::CreateConnection();
?>
复制代码 代码如下:
class DataBase
{
const AUTHOR="kym";
static $connectionString="http://127.0.0.1";
public static function CreateConnection()
{
echo(self::$connectionString." Success");
}
}
echo(DataBase::AUTHOR);
echo(DataBase::$connectionString);
DataBase::CreateConnection();
?>