search
HomeBackend DevelopmentPHP TutorialPHP的面向对象编程:开发大型PHP项目的方法(五)

使用类进行数据存储
  对于php和OOP一件非常好的事情就是,你可以很容易地定义一个类来操作某件事情,并且无论何时你想 用的时候都可以调用相应的类。假设你有一个HTML表单,用户可以通过选择产品ID号来选择一个产品。在数 据库中有产品的信息,你想把产品显示出来,显示它的价格等等。你拥有不同类型的产品,并且同一个动作 可能对不同的产品具有不同的意思。例如,显示一个声音可能意味着播放它,但是对于其它种类的产品可能 意味着显示一个存在数据库中的图片。你可以使用OOP或PHP来减少编码并提高质量:

  定义一个产品的类,定义它应该有的方法(例如:显示),然后定义对每一种类型的产品的类,从产品 类派后出来(SoundItem类,ViewableItem类,等等),覆盖在产品类中的方法,使它们按你的想法动作。

  根据数据库中每一种产品的类型(type)字段给类命名,一个典型的产品表可能有(id, type, PRice, description, 等等字段)...然后在处理脚本中,你可以从数据库中取出type值,然后实例化一个名为type 的对象:

--------------------------------------------------------------------------------

$obj=new $type();
$obj->action();

?>--------------------------------------------------------------------------------
  这是PHP的一个非常好的特性,你可以不用考虑对象的类型,调用$obj的显示方法或其它的方法。使用
这个技术,你不需要修改脚本去增加一个新类型的对象,只是增加一个处理它的类。

  这个功能很强大,只要定义方法,而不去考虑所有对象的类型,在不同的类中按不同的方法实现它们,然后在主脚本中对任意对象使用它们,没有if...else,也不需要两个程序员,只有高兴。

  现在你同意编程是容易的,维护是便宜的,可重用是真的吗?

  如果你管理一组程序员,分配工作就是很简单的了,每个人可能负责一个类型的对象和处理它的类。

  可以通过这个技术实现国际化,根据用户所选的语言字段应用相应的类就可以了,等等。


拷贝和克隆
  当你创建一个$obj的对象时,你可以通过$obj2=$obj来拷贝对象,新的对象是$obj的一个拷贝(不是一
个引用),所以它具有$obj在当时的状态。有时候,你不想这样,你只是想生成一个象obj类一样的一个新
的对象,可以通过使用new语句来调用类的构造函数。在PHP中也可以通过序列化,和一个基类来实现,但所
有的其它类都要从基类派生出来。



进入危险区域
  当你序列化一个对象,你会得到某种格式的字符串,如果你感兴趣,你可以调究它,其中,字符串中有
类的名字(太好了!),你可以把它取出来,象:

--------------------------------------------------------------------------------

$herring=serialize($obj);
$vec=explode(':',$herring);
$nam=str_replace("\"",'',$vec[2]);

?>--------------------------------------------------------------------------------
  所以假设你创建了一个"Universe"的类,并且强制所有的类都必须从universe扩展,你可以在universe
中定义一个clone的方法,如下:
--------------------------------------------------------------------------------

class Universe {
function clone() {
$herring=serialize($this);
$vec=explode(':',$herring);
$nam=str_replace("\"",'',$vec[2]);
$ret=new $nam;
return $ret;
}
}

//然后
$obj=new Something();

//从Universe扩展
$other=$obj->clone();

?>--------------------------------------------------------------------------------
  你所得到的是一个新的Something类的对象,它同使用new方法,调用构造函数创建出的对象一样。我不 知道这个对你是否有用,但是Universe类可以知道派生类的名字是一个好的经验。想象是唯一的限制。

  注意:我用的是PHP4,我写的有些东西在PHP3下可能不能工作。


上一页

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What are some common problems that can cause PHP sessions to fail?What are some common problems that can cause PHP sessions to fail?Apr 25, 2025 am 12:16 AM

Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

How do you debug session-related issues in PHP?How do you debug session-related issues in PHP?Apr 25, 2025 am 12:12 AM

Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

What happens if session_start() is called multiple times?What happens if session_start() is called multiple times?Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

How do you configure the session lifetime in PHP?How do you configure the session lifetime in PHP?Apr 25, 2025 am 12:05 AM

Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.

What are the advantages of using a database to store sessions?What are the advantages of using a database to store sessions?Apr 24, 2025 am 12:16 AM

The main advantages of using database storage sessions include persistence, scalability, and security. 1. Persistence: Even if the server restarts, the session data can remain unchanged. 2. Scalability: Applicable to distributed systems, ensuring that session data is synchronized between multiple servers. 3. Security: The database provides encrypted storage to protect sensitive information.

How do you implement custom session handling in PHP?How do you implement custom session handling in PHP?Apr 24, 2025 am 12:16 AM

Implementing custom session processing in PHP can be done by implementing the SessionHandlerInterface interface. The specific steps include: 1) Creating a class that implements SessionHandlerInterface, such as CustomSessionHandler; 2) Rewriting methods in the interface (such as open, close, read, write, destroy, gc) to define the life cycle and storage method of session data; 3) Register a custom session processor in a PHP script and start the session. This allows data to be stored in media such as MySQL and Redis to improve performance, security and scalability.

What is a session ID?What is a session ID?Apr 24, 2025 am 12:13 AM

SessionID is a mechanism used in web applications to track user session status. 1. It is a randomly generated string used to maintain user's identity information during multiple interactions between the user and the server. 2. The server generates and sends it to the client through cookies or URL parameters to help identify and associate these requests in multiple requests of the user. 3. Generation usually uses random algorithms to ensure uniqueness and unpredictability. 4. In actual development, in-memory databases such as Redis can be used to store session data to improve performance and security.

How do you handle sessions in a stateless environment (e.g., API)?How do you handle sessions in a stateless environment (e.g., API)?Apr 24, 2025 am 12:12 AM

Managing sessions in stateless environments such as APIs can be achieved by using JWT or cookies. 1. JWT is suitable for statelessness and scalability, but it is large in size when it comes to big data. 2.Cookies are more traditional and easy to implement, but they need to be configured with caution to ensure security.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function