Crazenezz
Crazenezz

Reputation: 3456

Cannot use public modifier on PHP class

I have very strong basic in Java, and when comes to PHP I got some problem with the OOP.

Please take a look at this two classes below:

Contacts.php

<?php 

    public class Contacts {

    }
?>

UnitTest.php

<?php

    require_once 'PHPUnit/Framework.php';
    include 'Contacts.php';

    class UnitTest extends PHPUnit_Framework_TestCase {

        public function testRead() {
            $temp = new Contacts();
        }
    }
?>

When I trying to test the UnitTest.php using phpunit I got this error message:

PHP Parse error:  syntax error, unexpected T_PUBLIC in
    /home/crazenezz/Projects/PHP/Demo/Class/Contacts.php on line 3

And after trial and error I remove the public modifier of Contacts class, and the test become success without error.

Contacts.php (After remove the public modifier)

<?php 

    class Contacts {

    }
?>

Can anyone explain why in PHP I cannot use the public as modifier of a class?

Upvotes: 1

Views: 341

Answers (2)

JTHouseCat
JTHouseCat

Reputation: 445

In PHP you only use the public modifier in front of variables and functions. In Java you can use the public modifier infront of a class, constructor, method, variables or interfaces. Why? because the languages are different. If you need notes on it to remind yourself I wrote something here explaining the difference between PHP modifiers and Java modifiers, as I too learned Java way before PHP. http://www.siteconsortium.com/h/D0000G.php

Upvotes: 0

deceze
deceze

Reputation: 522625

Because all classes are public in PHP. There's no such thing as a "private class".

Upvotes: 4

Related Questions