简单贴个代码,加深理解吧。
<?php
/*命名空间Col*/
namespace Col{
const INSTANCE=3;
class A {
private $a = 'private';
protected $b = 'protected';
public $c = 'public';
static $d = 'static';
public function __construct()
{
$this->e = '构造函数里这个变量声明在哪里啊,不用声明吗<br/>';
var_dump($this->e);
}
public function __set($property, $value)
{
echo ' set ' . $property . '=' . $value;
$this->$property=$value;
}
public function __get($property)
{
echo ' get ' . $property;
$this->$property = '取数值'; // invokes __set() !!
return $this->$property;
}
public function printItem($string)
{
echo '父亲的: ' . $string . PHP_EOL;
}
public function printPHP()
{
echo '哈哈哈,太爷有<br/>' . PHP_EOL;
}
}
class B extends A
{
public function constructMe()
{
$this->e = 'constructed2';
}
public function printItem($string)
{
return $this->getM($string);
}
public function getM($string){
echo $string;
$this->c = "我看看这个";
return false;
}
}
class C extends B
{
public function __construct()
{
parent::constructMe();
echo "孙子你牛X,赢在起跑线";
}
public function getC($str){
$aa = new static();
return $aa -> getM($str) || $aa->c;
}
}
echo " <br/>";
$a = new A();
$b = new B();
echo " <br/>";
echo ' 儿子访问下太爷公用的'.$b->c;
echo " <br/>";
echo ' 儿子访问下太爷静态的' .$b->d; //注意这种方式是爷爷定义了set,get方法才能调用的,正规::
echo " <br/>";
$c = new C();
echo " <br/>";
echo 'A class: ';
}
namespace Lin{
use \Col; //引入上面名字空间
$grandson = new Col\C();
$grandson->getM('<br/>参数来了啊');
var_dump($grandson->c);
echo "----------------------- <br/>";
$model = new Col\C();
$model->getC('<br/>瞎玩');
var_dump($model->c);
var_dump($model->getC('<br/>又在瞎玩'));
}
/*全局非命名空间代码*/
namespace {
const INSTANCE=4;
var_dump(\Col\INSTANCE);
}