开发者

Alternative to regular PHP Class

开发者 https://www.devze.com 2023-03-09 20:31 出处:网络
Generally when creating a PHP class I would do something as such class Foo { public function Foo(){} public function RandomFunction(){};

Generally when creating a PHP class I would do something as such

class Foo
{
    public function Foo(){}
    public function RandomFunction(){};
}
global $foo;
$foo = new Foo();
$foo->RandomFunction();

I have noticed that on the web people are frowning upon the global vars for classes but without it I would开发者_运维百科 not be able to access the class inside other functions.

Now an alternative to this would be using static classes as such:

class Foo
{
    static public function RandomFunction(){}
}
Foo::RandomFunction();

My Question is this, is this the best alternative to global vars for classes? Or is there a better way to go about it all together?


In good OO practice, if a class needs to access an instance of another class, you pass object in as a parameter and then access it's properties and methods from there.

If you have a well designed object model the code should be relatively clean and logical, however if you aren't planning on creating a strict OO application, you probably shouldn't worry about your classes being in global scope or not.


Think of your object like a bicycle. You own your bicycle, and can loan it to whomever you wish. They can use it and return it to you, and you will be able to keep track of who did what to your bike, and when.

If your bike is generally available to anyone in the world, however, your job of monitoring and controlling access to it will become exponentially more difficult. You will be hard-pressed to keep track of who is using your bike, when they are using it, and how they are (ab)using it.

Passing your objects (rather than declaring them globally) allows you to maintain stricter controls on your object and the data it contains.

0

精彩评论

暂无评论...
验证码 换一张
取 消