我对面向对象的php很安静。并且学习新的东西。现在我想在php中使用命名空间。我在1个目录中有2个文件。我想在使用命名空间的index.php文件中使用来自get_name()
的{{1}}函数,但不知道如何使用它。当我只是将文件class.php包含到index.php中时它工作正常,但我想使用命名空间。
的index.php
class.lib
class_lib.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);
?>
答案 0 :(得分:1)
您的信息:“函数名称在单词之间使用下划线,而类名称同时使用camelCase和PascalCase规则。”
因此,我将使用PascalCase
作为您的课程(避免使用下划线)。
<强>在MyLibrary /人/ ReadMethods.class.php 强>
namespace Person;
interface ReadMethods
{
public function read_age($age);
}
<强>在MyLibrary /人/ Person.class.php 强>
namespace Person;
abstract class Person
{
/* You should change your var to public/protected/private */
var $gender;
var $animal;
var $birds;
/* ... */
}
<强>在MyLibrary /人/行为强>
namespace Person;
use \Circle\Draw; // use != require
class Behaviour extends Person implements ReadMethods
{
function get_all()
{
return $this->people();
return $this->animals();
return $this->bird();
}
/* ... */
}
<强>在MyLibrary /平局/ Circle.class.php 强>
namespace Draw;
class Circle
{
public $rad;
function __construct($rad)
{
$this->rad=$rad;
}
function get_name($name)
{
return $this->rad * $this->rad * $name;
}
}
<强>的index.php 强>
/** Your custom autoloader **/
spl_autoload_register( function( $sClass) {
/* Check File Existence. Define a path for your library folder */
if(file_exists(YOUR_LIBRARY."{$sClass}.class.php")){
if( !class_exists($sClass) ){
require_once YOUR_LIBRARY."{$sClass}.class.php";
}
}
});
$doerte= new Person\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');
关于关键字使用:Import class conditionally with the keyword 'use'
我希望它会有所帮助,而且我已经明确了。