如何从包含的php类调用方法?

时间:2014-02-09 10:59:49

标签: php

home.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

3 个答案:

答案 0 :(得分: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;
    }
}

答案 1 :(得分:1)

使用

$sampleClass = new main();

答案 2 :(得分:0)

你应该使用

$sampleClass = new main();