2017-10-13 12 views
1

PHP OOPの新人です。別のクラスのあるクラスのメンバーデータと関数にアクセスしたいという問題があります。私はそれをグーグルだが、完璧な解決策を得ていない。私はここに新しいですPHPの他のクラスのあるクラスの関数とデータにアクセスする方法

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

基本的な知識が必要なので、最初に理論をお読みください(http://php.net/manual/en/language.oop5.php) – Neodan

答えて

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(); 
    } 
} 
+0

私の機能は静的です。コードに誤りを追加するのを忘れました。 –

0

あなたがアクセスするデータを持つクラスをインスタンス化する必要があります。また、データを静的に定義し、インスタンス化せずにアクセスすることもできます。これを試してみてください「先生の名前」のようないくつかのデータを返すために、あなたの先生()関数を作る

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` 
} 
} 

はこれを見てください。これは、学校のクラスからライブラリクラスを継承するphpクラスです。

main関数は、学校のクラスからデータを取得するライブラリクラスを介して必要なデータにアクセスします。

・ホープこれはあなたが、その後techer名前を返すクラス `school`で関数を作成し、` "` $ techer_name =" 属性を作成する必要があります

<?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(); 
関連する問題