何时声明类的属性? [英] When To Declare Properties Of A Class?

查看:44
本文介绍了何时声明类的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚接触 PHP OOP,我不清楚需要在类开始时声明哪些属性.

I'm just getting into PHP OOP and I'm unclear on what properties I need to declare at the start of a class.

我是否声明属性:

A:那是方法的参数?

B:不是方法的参数但仍在方法中?

B: are not arguments for methods but are still within a method?

C:从方法返回的?

例如编辑这是我正在尝试创建的示例用户类

Edit For Example Here's an example userclass I'm trying to create

class user
{
public function selectMember($username,$password)
$query = "SELECT * FROM users WHERE username='$username' && password='$password'";
return $query;
}

所以我只能在类的顶部声明 $query 吗?

So I would have to declare $query only at the top of the class?

推荐答案

我对这些事情的看法是,对象是现实生活对象的代码表示(废话).上面的汽车例子是一个很好的例子.对于大多数现实生活中的对象,都有属性和动作.如果我们的对象是人,它将具有姓名、身高、体重、头发颜色等属性.然后,我们的人就会有行动,比如跑、睡、吃.

The way I think of these things is that an object is a code representation of a real life object (duh). The car example above is a good one. For most real life objects there are attributes and actions. If our object is person, it will have attributes like name, height, weight, hair color. Then, our person will have actions, like run, sleep, eat.

动作是方法,属性是属性.属性将在动作中使用,或者由程序的其他部分使用,这些部分需要检查您的对象的状态,IE,您的程序的另一部分会询问此人它现在有多高.

The actions will be methods and the attributes will be properties. Properties will either be used in the actions or by other parts of the program which need to check the state of your object, IE, another part of your program asks the person how tall it is right now.

在大多数情况下,返回值和参数不会是属性.一个值得注意的例外是用于实例化对象的参数,因为其他方法通常需要这些参数.至于在方法中使用的变量,如果它们定义对象的整体状态,则这些应该是属性,但是如果您在方法内部创建变量,例如计数器,则仅需要完成该方法的目标,将其作为对象的属性没有任何意义.

In most cases, return values and arguments will not be properties. A notable exception would be arguments you use to instantiate an object, as those will typically be needed by your other methods. As far as variables used within a method, these should be properties if they define the overall state of the object, but if you are creating a variable, like a counter, inside your method, that is just needed to accomplish the goal of the method, it doesn't make sense for it to be a property of your object.

我会从较少的属性方面犯错开始.如果你到了需要一个属性来完成某事的地步,然后创建它.除非我有直接需求,否则我不会创建它们.通过这种方式,您将开始了解对象需要哪些属性才能在逻辑上发挥作用.

I would start out by erring on the side of fewer properties. If you get to a point where you need a property to accomplish something, then create it. I wouldn't create them until I have a direct need. This way, you'll begin to get a feel for what properties an object will need in order to function logically.

我希望这有点道理.

这篇关于何时声明类的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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