2012-08-26 42 views
1

我分别创建了两个php类。这些是Student.php和Main.php这是我的代码。如何使用PHP调用另一个类中的方法

这是我Student.php

<?php 

class Student { 

private $name; 
private $age; 

function __construct($name, $age) { 
    $this->name = $name; 
    $this->age = $age; 
} 

function setName($name){ 
    $this->name = $name; 
} 

function setAge($age){ 
    $this->age = $age; 
} 

function getName() { 
    return $this->name; 
} 

function getAge() { 
    $this->age; 
} 

function display1() { 
    return "My name is ".$this->name." and age is ".$this->age; 
} 

} 

?> 

这是我Main.php

<?php 

class Main{ 

function show() { 
    $obj =new Student("mssb", "24"); 
    echo "Print :".$obj->display1(); 
} 

} 

$ob = new Main(); 
$ob->show(); 

?> 

所以我的问题是,当我打电话taht show方法它给致命错误: '学生'没有找到这里有什么问题。是否需要导入或什么?请帮帮我。

回答

2

在Main.php文件添加

require_once('Student.php') 

(顶部)或之前包括任何其他文件...

2

PHPUnit documentation说过去常说,包括/需要的PHPUnit/Framework.php如下:

require_once ('Student.php'); 

截至PHPUnit的3.5,有一个内置的自动加载类,将您处理该问题:

require_once 'PHPUnit/Autoload.php' 
0

这是值得看看PSRs。特别是PSR-1

其中一项建议是,

Files SHOULD either declare symbols (classes, functions, constants, etc.) or cause side-effects (e.g. generate output, change .ini settings, etc.) but SHOULD NOT do both

采用此方法将有望使像你遇到不常见的一个问题。

例如,通常只有一个文件负责加载所有必需的类文件(最常见的是通过autoloading)。

当一个脚本初始化时,它应该做的第一件事就是包含负责加载所有必需类的文件。

2

您可以使用require_once('Student.php'),或者您可以使用PHP5新功能命名空间。举个例子,假设你的Student.php在一个叫做student的dir中。然后,随着Student.php的第一线,你可以把

<?php  
namespace student; 

class Student { 
} 

然后在你的Main.php

<?php  
use student\Student; 

class Main { 
} 
相关问题