Accessing a public method using scope variable

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
novito
Forum Commoner
Posts: 26
Joined: Mon Apr 07, 2008 11:08 am

Accessing a public method using scope variable

Post 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 :)
User avatar
novito
Forum Commoner
Posts: 26
Joined: Mon Apr 07, 2008 11:08 am

Re: Accessing a public method using scope variable

Post 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...
User avatar
Eran
DevNet Master
Posts: 3549
Joined: Fri Jan 18, 2008 12:36 am
Location: Israel, ME

Re: Accessing a public method using scope variable

Post 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
User avatar
MindOverBody
Forum Commoner
Posts: 96
Joined: Fri Aug 06, 2010 9:01 pm
Location: Osijek, Croatia

Re: Accessing a public method using scope variable

Post by MindOverBody »

It will break on error only if you use $this word inside method
User avatar
novito
Forum Commoner
Posts: 26
Joined: Mon Apr 07, 2008 11:08 am

Re: Accessing a public method using scope variable

Post by novito »

Thanks guys,

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