Ali.Rashidi
Ali.Rashidi

Reputation: 1462

How to call methods from included php classes?

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

Now when I do that I receive an error and it says:

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

Upvotes: 1

Views: 42

Answers (3)

Simone Nigro
Simone Nigro

Reputation: 4887

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

Upvotes: 2

honzaik
honzaik

Reputation: 273

use

$sampleClass = new main();

Upvotes: 1

cornelb
cornelb

Reputation: 6066

You should use

$sampleClass = new main();

Upvotes: 0

Related Questions