Log in

View Full Version : declaring variable and function in PHP class



pman
03-16-2008, 06:01 PM
I'm trying to get into writing OOP in PHP. Using PHP5. I know the basic structure of a class, variable and functions, but getting confused when looking at different tutorial.

Inside a class, some are declaring function like:


public function doSomething()

while others are writing


public doSomething()

Some are even writing


function doSomething()

Now, what is the difference in here? Who is right? I think the first two are more like how OOP should be (correct me if I'm wrong).

And, what about declaring variables? I believe it should it be:


public $myVar

Hope you can clarify my confusion here. Thanks

alexjewell
03-16-2008, 08:12 PM
Check out PHP.net's explanation:

http://www.php.net/public

boogyman
03-17-2008, 12:53 PM
public function doSomething()
the first one is syntactically the most correct, however PHP5 might possibly allow the others

Master_script_maker
03-17-2008, 07:48 PM
if it is not declared PHP 5 declares it as public, but it is a good practice to always define it. Here is how the visibility works:


class myClass {
public $public="public";
private $private="private";
protected $protected="protected";

public function print_vars() {
echo $this->public;
echo $this->private;
echo $this->protected;
}
}
class myClass2 extends myClass {
public function print_vars2() {
echo $this->public;
echo $this->private;
echo $this->protected;
}
}
$test1=new myClass;
$test2=new myClass2;
Here is how it would output:
echo $test1->public; - "public"
echo $test1->private; - fatal error
echo $test1->protected; - fatal error
echo $test2->public; - "public"
echo $test2->private; - undefined
echo $test2->protected; - fatal error
$test1->print_vars(); - "public" "private" "protected"
$test2->print_vars2(); - "public" undefined "protected"