0

new to the site. Have a quick questions.

It is safe or to load objects in one file to call when needed, such as:

objects.php

<?php
require 'autoload.php';

//create global objects
$obj = new Object();
$obj2 = new User();
$obj = new Bus();
?>

header.php

<?php
require 'objects.php';

echo 'Hello ' . $obj2->getName();
?>

Thanks in advance.

4

2 に答える 2

1

It's smarter to instantiate objects only when you need them. Creating objects takes some time and some memory. You also want to be able to know exactly what objects are in use at any given execution point in your come when you come back to change something later.

If you instantiate a bunch of objects you don't need, you'll inevitably find yourself wanting to make a change but having to spend time figuring out if you've already use $obj2 or if it's safe to start using it on line 350. If you don't name your objects more descriptively, you'll also find that you'll reuse variable names, which will cause confusion when your object doesn't act the way you expect. For example, in your code, $obj is a Bus, not an Object. If you were expecting an object, you'd be confused.

于 2012-06-25T21:42:26.870 に答える
0

If you don't need the object then you shouldn't load it. However I'm guessing you are trying to create some global store of information and I'm going to assume you need it this way. With that being said it would be a better idea to use static objects so you don't run into scope issues.

Static objects don't normally get instantiated and would just be used like:

User::setName('Bob');
echo 'Hello ' . User::getName();
于 2012-06-25T21:53:19.060 に答える