Page 1 of 1

Accessing a public method using scope variable

Posted: Sun Aug 08, 2010 5:58 am
by novito
Hi there,

I'm trying to learn OOP-PHP, and I have found something that surprises me. I have the following code:

Code: Select all

<?php
class CalledClass
{
    function go2()
    {
		echo "hello world";
    }
}

class CallerClass
{
    function go()
    {
        CalledClass::go2();
    }
}

$obj = new CallerClass();
$obj->go();
How is it possible that the double colon let me go inside the method of that independent class (not base class) without any problems? Isn't the double colon just used for static and constants?

Thanks :)

Re: Accessing a public method using scope variable

Posted: Sun Aug 08, 2010 6:36 am
by novito
My doubts are related to the need of using "static" in order to access a method without creating an object. For example, this following code works, without creating the method static:

Code: Select all

<?php
class CalledClass
{
    function go2()
    {
		echo "hello world";
    }
}

CalledClass::go2();

?>
Wouldn't this be violating the encapsulation of the class CalledClass?

Thanks...

Re: Accessing a public method using scope variable

Posted: Sun Aug 08, 2010 9:15 am
by Eran
PHP should be issuing a warning (but not a fatal error) when you try to access a non static method as static. I suggest you turn on display_errors and set error_reporting to the strictest level

Re: Accessing a public method using scope variable

Posted: Sun Aug 08, 2010 9:38 am
by MindOverBody
It will break on error only if you use $this word inside method

Re: Accessing a public method using scope variable

Posted: Sun Aug 08, 2010 10:53 am
by novito
Thanks guys,

I will enable those variables, and let's see if it shows the warning :)