【发布时间】:2014-10-25 16:41:23
【问题描述】:
我对面向对象的 php 很陌生。并在其中学习逐步明智的新事物。现在我想在 php 中使用命名空间。我在 1 个目录中有 2 个文件。我想在 index.php 文件中使用 class.lib 中的 get_name() 函数,使用命名空间,但不知道如何使用它。当我简单地将文件 class.php 包含到 index.php 中时,它工作正常,但我想改用命名空间。
index.php
<?php
interface read_methods
{
public function read_age($age);
}
abstract class person
{
var $gender;
var $animal;
var $birds;
abstract function group($group);
function people($value)
{
$this->gender=$value;
}
final public function animals($value)
{
$this->animal=$value;
}
function bird($value)
{
$this->birds=$value;
}
}
class behaviour extends person implements read_methods
{
function get_all()
{
return $this->people();
return $this->animals();
return $this->bird();
}
function non_human($nonhuman)
{
$this->non_human=$nonhuman;
}
function read_age($age)
{
try {
if($age > 20) {
throw new Exception('Age exceeds!');
}
else
{
$this->age=$age;
}
}
catch(Exception $e)
{
echo 'There has been an error for the age value : '.$e->getMessage().' <br>' ;
}
}
function group($group)
{
return $this->group=$group;
}
}
$doerte= new behaviour();
$doerte ->people(array('male','female'));
$doerte ->animals(array('fish','whale'));
$doerte ->bird(array('parrot','crow'));
$doerte->non_human('alien');
$doerte->read_age('19');
$doerte->group('living_things');
print_r($doerte);
?>
class_lib.php
<?php
class Circle
{
public $rad;
function __construct($rad)
{
$this->rad=$rad;
}
function get_name($name)
{
return $this->rad * $this->rad * $name;
}
}
$Cir = new \Circle(5);
echo $Cir->get_name('30');
【问题讨论】:
-
您的代码有效吗?
var $gender;已“弃用”。如果是这种情况,您不能使用namespace,因为您需要 PHP >= 5.3.0 -
我的代码运行良好,我现在使用的是 php 5.3
标签: php oop namespaces