need help understanding the declaration of class properties
i was following an ACL tut. which has used this piece of code.
class ACL
{
var $perms = array();
var $userID = 0;
var $userRoles = array();
function __constructor($userID = '')
{
}
}
however i am unable to understand some of the above declarations.
a) the class property is declared starting with var keyword in the above class, in data encapsulation is it not necessary we use public,private, or protected keywords before the declaration of the property.? is the above method meant for PHP4 开发者_运维知识库? or will it work for php5 too?
b) my IDE(Panic Coda). takes __construct as the correct syntax for constructor. the above code has used __constructor . which one is correct ? to my knowledge in PHP4 the constructor name should be the same as class name if that is the case then is __construct and __constructor one and the same in PHP5?
thank you
a) The var
keyword is indeed probably meant for PHP 4 compatibility. var
is equivalent with PHP 5's public
. It will work in PHP 5 as well, but seeing as PHP 4's time has passed, it is safe to move on to public
, private
, and protected
.
b) __construct
, or the name of the class for a PHP 4 compatible declaration, is the only correct way. __constructor()
will not declare a constructor method.
In PHP4 all members and methods are static and public. var
is definitely PHP4 syntax. In PHP5 you should use public
, private
and protected
.
__construct() is correct method name for constructor. Since PHP 5.3 method that has the same name as the class is no longer treated as a constructor - it's just a regular method.
You should definitely find an up to date tutorial.
This example class has mix of PHP4 and PHP5.
- Variable declarations have used PHP4 syntax and it is 100% OK with PHP5 too.
- In PHP5, you can declare member variables as
private
,public
orprotected
. - Even PHP5 functions can be
private
,public
orprotected
. - But these accessor types are not compatible with PHP4.
- In PHP5, you can declare member variables as
- Class constructor have used PHP5 syntax, but it's not compatible with PHP4.
Since you're a learner, please do adhere to PHP's naming convention, name the script file containing classes using class name. And don't use more than one class inside the same script file. All PHP files must be ended up with the extension .php
to ensure security.
Further you can have static methods inside classes (don't mix static and dynamic methods inside the same class), and they can be invoked without creating objects such as Http::DoPost(...)
. But then $this
cannot be used inside static methods.
精彩评论