如果我在php类中有超过一百个数据成员(变量),它会明显变慢吗?

问题描述:

I have a PHP class called Vehicle that manages everything pertaining to cars,motorbikes and trucks. I have over a hundred private variables that is associated with every db field in each of the tables cars,bikes,trucks.

For example: A car has: -Fuel Consumption -Max horsepower -Max torque .. etc.. so i have data members

private $fuel;
private $horsepower;
private $toque;

When I do a database query to find a car by id, i store all the rows inside their corresponding variables.

The car table has about 50 fields, the bikes table has 30 fieldsand the trucks 30 fields. So there is over 110 data members.

Is there a better way to do that?

我有一个名为Vehicle的PHP类,用于管理与汽车,摩托车和卡车有关的所有内容。 我有超过一百个私人变量与每个汽车,自行车,卡车的每个数据库字段相关联。 p>

例如: 汽车有: -燃料消耗量 n-Max马力 -Max扭矩..等.. 我有数据成员 p>

  private $ fuel; 
private $ horsepower; 
private $ toque; 
   code>  pre> 
 
 

当我通过id查找汽车的数据库查询时,我将所有行存储在相应的变量中。 p>

车桌有大约50个区域,自行车桌有30个区域,卡车有30个区域。 所以有超过110个数据成员。 p>

有更好的方法吗? p> div>

Inheritance and polymorphism are your friends! The Car should be one class (with 50 properties), bike - another one (30 properties), truck - another (30 properties). They all should extend the Vehicle base class

You can try lazy loading: In the constructor (or whatever function that gets the car id) you only store the id in the class, and for every other variable you only load it from the DB when you really need it.

Number of variables rarely has an impact except in code management. Object Oriented Programming utilizing polymorphism is the first step to keeping your domain objects in good order. Once you have that, you can look into an ORM (Object Relational Mapping) for getting variables to and from the db PHP Active Record would be a good place to start.

Also, when you say 'bikes have 30 rows', you mean fields, right? Typically if you have a database table for 'bikes', each row is a different bike and each field is a different attribute of a given bike.