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

查看:31
本文介绍了什么时候应该在 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 也同样可访问和可用——它似乎表现得好像我已经声明了它作为公共.

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天全站免登陆