我是PHP OOP的新手,我有一个问题,我想在另一个类中访问一个类的成员数据和函数。我谷歌但没有得到任何完美的解决方案。
这是我的示例代码:
class school{
public function teacher()
{
$teacher_name='Ali Raza';
}
public static function students()
{
echo"STUDENT DATA: Jhon Deo";
}
}
class library{
public function teacher_name()
{
// Now here i want to acces the name of teacher form above class function teacher.
}
public function student_name()
{
// Now here i want to access the member function(students) from school class.
}
}
我是新来的。提前谢谢。
答案 0 :(得分:0)
尝试将类学校的功能访问到类库函数中:
class school {
public function teacher()
{
$teacher_name='Ali Raza';
}
public function students()
{
echo"STUDENT DATA: Jhon Deo";
}
}
class library {
public function teacher_name()
{
// Now here i want to acces the name of teacher form above class function teacher.
}
public static function student_name()
{
echo School::students();
}
}
答案 1 :(得分:0)
您需要实例化包含您要访问的数据的类。或者,您可以定义数据静态并访问它而无需实例化。
看看这个:
class library{
private $getTeacherInstance;
public function teacher_name()
{
if(!$getTeacherInstance) // if instance is not created
$this->getTeacherInstance = new school(); // then get a new instance
return $this->getTeacherInstance->teacher(); // call the method exists inside `school class`
}
}
让您的teacher()函数返回一些数据,如"教师姓名"
答案 2 :(得分:0)
试试这个。这是一个继承从学校类到库类的php类。
main函数将访问从类类中获取数据的库类所需的数据。
希望这有帮助
<?php
class school{
public $teacher_name;
public $students_name;
public function getTeacherName(){
return $this->teacher_name;
}
public function setTeacherName(){
$this->teacher_name = "Ali Raza";
}
public function getStudentName(){
return $this->students_name;
}
public function setStudentName(){
$this->students_name = "Ali Raza";
}
}
/**
*
*/
class library extends school
{
//this will get the value from class school
}
function showAll(){
$showAll = new library();
$showAll->setTeacherName();
echo "Teacher Name: " . $showAll->getTeacherName() . '<br>';
echo "Studnet Name: ". $showAll->getStudentName();
}
showAll();