PHP 变量 vs 数组 vs 对象 [英] PHP Variable vs Array vs Object
问题描述
这可能被认为是一个非常愚蠢的问题,但我正在为网站组装一个简单的模板系统,并试图跟踪我的变量使用情况并保持一切整洁.
This is probably considered a really silly question, but I'm in the process of putting together a simple template system for a website and am trying to keep track of my variable usage and keep everything neat and tidy.
你能告诉我以下方法是否有任何优点/缺点:
Can you tell me if there is any advantage/disadvantage to the following methods:
简单变量:
$tpl_title = 'my title'
$tpl_desc = 'my text'
数组:
$tpl['title'] = 'my title'
$tpl['desc'] = 'my text'
对象:
$tpl->title = 'my title'
$tpl->desc = 'my text'
我最喜欢对象方法,因为它在 html 中回显而不是数组时看起来很干净,而且它可以以类似数组的方式使用?但是,我想知道以这种方式使用对象是否被认为是不好的做法或引入了不必要的开销?
I like the object method the best as it looks clean when echo'd within html as opposed to arrays and afaik it can be used in an array-like way? However, what I want to know is whether using objects in this way is considered bad practice or introduces unneccesary overheads?
推荐答案
我认为这是不必要的开销.以面向对象的方式做你正在谈论的事情只会意味着在你的类中你只会创建一堆变量......就像你在第一个例子中指定的那样.
I would consider it unnecessary overhead. Doing what you are talking about in an object oriented way only means that inside your class you will have done nothing more than create a bunch of variables... just as you specified in your first example.
在我看来,数组是最好的方法.您只使用一个变量……您也可以将其集成到您的类中.所以不是 $tpl->title,你可能有 $tpl->text['title']
The array is the best way to go in my opinion. You are only using one variable... and you can also integrate it into your Class. So instead of $tpl->title, you may have $tpl->text['title']
这篇关于PHP 变量 vs 数组 vs 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!