问题描述
我正在尝试学习如何在PHP中最好地使用OOP.请注意,即使我研究了这个新的世界"的理论,我显然也没有进入OOP思维.
I'm trying to learn how to best use OOP in PHP. Please be aware that even if I studied the theory of this new "world" I didn't enter the OOP thinking yet obviously.
使用普通的分离函数并将它们作为方法放在类中有什么区别?
What's the difference between using normal, separated functions and putting them in a class as methods?
比方说,我有一堂课叫做商店".
Let's say I have a class called "shop".
它具有以下方法:检索项,删除项,更新项,添加项
It has these methods: retrieveitems, deleteitems, updateitems, additems
除了我可以使用简单的"$ this"在方法内部调用方法外,将它们放入没有类的不同函数之间有什么区别?我的意思是,例如,我仍然可以在函数retrieveitems中调用函数deleteitems,对吗?即使不在课堂上?
Except for the fact that I can call methods inside methods with a simple "$this", what is the difference between putting them in different functions without a class? I mean, for example, I still can call function deleteitems inside function retrieveitems right? Even if not in a class?
请帮助我了解我所缺少的内容.
Please help me understand what I'm missing.
推荐答案
OOP提供了封装功能.
OOP provides, among other things, encapsulation.
class Shop {
function __construct($items) {
$this->inventory = $items;
}
function deleteItem($item) {
$key = array_search($item, $this->inventory);
if ($key !== false)
unset($this->inventory[$key]);
}
}
现在您可以创建实例:
$computerShop = new Shop(array('ram', 'monitor', 'cpu', 'water'));
$hardwareStore = new Shop(array('hammer', 'screwdriver', 'water'));
他们每个人都是彼此独立的.如果我执行$computerShop->removeItem('water')
,则$hardwareStore
的inventory
中仍应包含water
. (看到实际效果.)执行此过程的方法更加麻烦.
And each one of them is independent from each other. If I do $computerShop->removeItem('water')
, $hardwareStore
should still have water
in their inventory
. (see it in action) Doing this the procedural way is much messier.
关于OOP的另一个有趣的事情是,您可以使用继承和多态性:
Another cool thing about OOP is that you can use inheritance and polymorphism:
class Animal {
function eat() {
$this->hungry = false;
}
abstract function speak();
}
class Cat extends Animal {
function speak() {
echo 'meow!';
}
}
class Dog extends Animal {
function speak() {
echo 'woof!';
}
}
现在,即使Cat
和Dog
都未在其类中明确声明,也可以调用方法eat()
-它是从其父类Animal
继承的.他们还具有speak()
方法,可以执行不同的操作.很好,是吧?
Now both Cat
and Dog
s can call the method eat()
even though they are not explicitly declared in their classes - it's been inherited from their parent class Animal
. They also have a speak()
method that does different things. Pretty neat, huh?
这篇关于在PHP中使用普通函数和类方法有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!