Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
812 views
in Technique[技术] by (71.8m points)

oop - When should I declare variables in a PHP class?

I'm new to the OOP paradigm, so there's probably a simple explanation for this question...

Do you always need to declare public object-wide variables in a class? For example:

<?php

class TestClass
{
    var $declaredVar;

    function __construct()
    {
        $this->declaredVar = "I am a declared variable.";
        $this->undeclaredVar = "I wasn't declared, but I still work.";
    }

    function display()
    {
        echo $this->declaredVar . "<br />";
        echo $this->undeclaredVar;
        echo "<br /><br />"; 
    }
}

$test = new TestClass;
$test->display();

$test->declaredVar = "The declared variable was changed.";
$test->undeclaredVar = "The undeclared variable was changed.";

$test->display();

?>

In this code, even though $declaredVar is the only declared variable, $undeclaredVar is just as accessible and useable--it seems to act as if I had declared it as public.

If undeclared class variables are always accessible like that, what's the point of declaring them all up front?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

That variable isn't uninitialized, it's just undeclared.

Declaring variables in a class definition is a point of style for readability. Plus you can set accessibility (private or public).

Anyway, declaring variables explicitly has nothing to do with OOP, it's programming-language-specific. In Java you can't do that because variables must be declared explicitly.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...