2014-02-09 49 views
0

home.php如何從包含的PHP類中調用方法?

<?php 
include 'myClass.php'; 

$sampleClass=main; 
$sampleClass->renderHtml(); 

?> 

myClass.php

<?php 
class main 
{ 
    public $var="apple"; 

    public function renderHtml() 
    { 
     echo "This is $var"; 
     return; 
    } 
} 

現在,當我這樣做,我收到一個錯誤,它說:

Fatal error: Call to a member function renderHtml() on a 
non-object in C:\wamp\www\home.php on line 5 

回答

2
include 'myClass.php'; 

// first create a new object 
$sampleClass = new main(); 

// call object method 
$sampleClass->renderHtml(); 

myClass.php

class main 
{ 
    public $var = "apple"; 

    public function renderHtml() 
    { 
     echo "This is " . $this->var; 
    } 
} 
+0

注意:未定義的變量:用C VAR:\ WAMP \ WWW \ myClass.php上線8 –

+0

好吧,我已經更新了我的答案。 .. –

+0

非常感謝你:) –

0

您應該使用

$sampleClass = new main(); 
1

使用

$sampleClass = new main(); 
相關問題