什么时候应该在PHP类中声明变量? [英] When should I declare variables in a PHP class?

查看:62
本文介绍了什么时候应该在PHP类中声明变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是OOP范式的新手,所以可能对此问题有一个简单的解释...

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();

?>

在此代码中,即使$declaredVar是唯一声明的变量,$undeclaredVar也是可访问和可用的-似乎就像我将其声明为public一样.

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?

推荐答案

该变量不是未初始化的,只是未声明.

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).

无论如何,显式声明变量与OOP无关,它是特定于编程语言的.在Java中,您不能这样做,因为必须显式声明变量.

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.

这篇关于什么时候应该在PHP类中声明变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆