PHP——对象
<?php/*
* 创建一个类
*/
class Hello{
private $s='Hello world';
//function __set($name,$value){
//echo '该属性不存在<br/>';
//}
//function __get($name){
//echo '<br/>对象没有属性'.$name;
//}
public function setS($s){
if ($s!=0){
$this->s=$s;
}else{
$this->s='s变量的值不能为0';
}
}
public function getS(){
return $this->s;
}
public function printHello(){
echo $this->s;//not $s!!!调用属性不使用$操作符,而采用->操作符
}
}
$b=new Hello();
$b->printHello();
/*
* 动态增加对象的属性
*/
//$b->other='test';
//echo '<br/>'.$b->other;
$b->setS(0);
echo '<br/>'.$b->getS();
echo '<br/>';
//print_r(get_defined_constants());
?>
<?php
/*
* define vs const
*/
define('PI', '3.14');
echo constant('PI');
define('AREA', 3.14*100*100);
echo '<br/>'.constant('AREA');
class MyClass{
const PI=3.14;//const class scope
//const AREA=3.14*100*100;// error not support expression
function showPi(){
echo '<br/>'.self::PI;//use 'self'
}
}
$myClass=new MyClass();
$myClass->showPi();
echo '<br/>'.MyClass::PI;//out class
?>
<?php
class Foo{
private $s;
private static $ss;//静态属性,又称类属性
function __construct($s){//构造函数
$this->s=$s;
self::$ss=$s.$s;
echo '<br/>s is '.$this->s;
echo '<br/>ss is '.self::$ss;
}
function __destruct(){//析构函数
//close resource
}
}
new Foo(1);
?>
页:
[1]