Ben
Ben

Reputation: 5777

PHP accessing functions within a function

I'm really new to PHP classes and I was just wondering how to access functions within a PHP Class.

For example:

<?PHP
$cn = "myClass";
$myClass = new $cn;

class myClass
{
    function __construct()
    {
        doSomething(); // ?
    }
    private function doSomething() {
        echo "doSomething accessed!<br />";
    }
}
?>

How would I access doSomething() within the class? Any help would be much appreciated.

Upvotes: 0

Views: 68

Answers (1)

Mihai Iorga
Mihai Iorga

Reputation: 39724

You have to use $this:

<?PHP
$cn = "myClass";
$myClass = new $cn;

class myClass
{
    function __construct()
    {
        $this->doSomething(); // ?
    }
    private function doSomething() {
        echo "doSomething accessed!<br />";
    }
}
?>

The pseudo-variable $this is available when a method is called from within an object context. $this is a reference to the calling object.

Upvotes: 5

Related Questions