search
HomeBackend DevelopmentPHP TutorialIntroduction to the extension functions of the memcache class

This article mainly introduces the extension function of the memcache class. It has a certain reference value. Now I share it with you. Friends in need can refer to it

Memcache — Memcache class

/****connect****/
1.Memcache::connect – Create a Memcache object
Syntax: bool Memcache::connect ( string $host [, int $port [, int $timeout ]] )
Returns TRUE if successful, returns FALSE if failed
Case reference: $memcache_obj->connect('memcache_host', 11211);

2.Memcache::pconnect – Create a Memcache Persistent connection object
Syntax: bool Memcache::pconnect (string $host [, int $port [, int $timeout ]] )
Returns TRUE if successful, returns FALSE if failed
Parameters:
$host: Points to the host of the link that memcached is listening to. This parameter will have another special connection method unix:///path/to/memcached.sock, which uses unix domain name sockets. In this case, The port must be set to 0
$port: Points to the port of the link that memcached is listening to. In the case of unix domain name sockets, the port must be set to 0
$timeout: The number of seconds used to connect to the daemon. When When you change the default value of 1 second, you need to consider that if your connection is too slow, you may lose the advantages of caching.

/****Add to****/ ※Please note that when adding an object, you must use a new class name
1.Memcache::set – Add a value, if it already exists, overwrite it
Syntax: bool Memcache::set ( string $key , mixed $var [, int $flag [, int $expire ]] )
Add a value, if it already exists, overwrite it; return TRUE if successful, return FALSE if failed .

2.Memcache::add – Add a value, if it already exists, return false
Syntax: bool Memcache::add ( string $key , mixed $var [, int $flag [, int $expire ]] )
Returns TRUE if successful, returns FALSE if failed. If the $key value already exists, FALSE will be returned
Case reference: $memcache_obj->add('var_key', 'test variable', false, 30);

3.Memcache::replace - Overwrite an existing key
Syntax: bool Memcache::replace (string $key, mixed $var [, int $flag [, int $expire]])
Return TRUE if successful , returns FALSE on failure. If the $key value already exists, FALSE will be returned.
Parameters:
$key: The key value to be stored.
$var: The stored value, character type and integer type will be saved as the original value, other types will be automatically serialized and saved later.
$flag: Whether to use MEMCACHE_COMPRESSED to compress the stored value, true means compression, false means no compression.
$expire: The expiration time of the stored value. If it is 0, it means it will not expire. You can use a unix timestamp or description to represent the time from now, but when you use seconds to express it, it should not exceed 2592000 seconds. (meaning 30 days).

/****Get value****/
1.Memcache::get – Get a key value
Syntax: string Memcache::get ( string $key [, int &$flags ] )
        array Memcache::get (array $keys [, array &$flags])
If successful, return the value corresponding to the key, if failed, return false.
Parameters:
$key is Key value or an array value of a key.
$flags If this parameter exists, then $flags is related to the value written to this parameter. These $flags are similar to the $flags in the Memcache::set() function.

/****delete****/
1.Memcache::delete – delete a key value
Syntax: bool Memcache::delete ( string $key [, int $timeout ] )
Return TRUE if successful, return FALSE if failed.

2.Memcache::flush – Clear all cached data
Syntax: bool Memcache::flush (void)
Returns TRUE if successful, returns FALSE if failed.

/****Modify value****/ ※Change the stored value
1.Memcache::decrement – ​​Subtract the value in a saved key
Syntax: int Memcache: :decrement ( string $key [, int $value ] )
If successful, return the reduced value, if failed, return false.

2.Memcache::increment - Add the value in a saved key
Syntax: int Memcache::increment (string $key [, int $value])
If On success, the reduced value is returned, and on failure, false is returned.
Parameters:
Key: the name of the key you want to reduce
Value: the value you want to reduce
Case reference: $memcache->increment('test_item', 4);

/****closure****/
1.Memcache::close – Close a Memcache object
Syntax: bool Memcache::close (void)
Returns TRUE if successful, returns if failed FALSE.

/****Configuration****/
1.Memcache::addServer – Add a server address that can be used
Syntax: bool Memcache::addServer (string $host [, int $ port [, bool $persistent [, int $weight [, int$timeout [, int $retry_interval [, bool $status [, callback $failure_callback ]]]]]] )
Returns TRUE if successful, otherwise Return FALSE.
Parameters:
Whether $persistent is a persistent connection
$weightThe weight of this server among all servers

2.Memcache::setServerParams – Modify server parameters at runtime
Syntax: bool Memcache::setServerParams ( string $host [, int $port [, int $timeout [, int$retry_interval [, bool $ status [, callback $failure_callback ]]]]] )
Returns TRUE if successful and FALSE if failed.
Parameters:
$host server address
$port server port
$timeout duration of connection
$retry_interval Interval time between connection retries, the default is 15, set to -1 No retry
$status controls the online status of the server
$failure_callback allows setting a callback function to handle error messages.

/****Get parameters****/
2.Memcache::getServerStatus – Get the status of the running server
Syntax: int Memcache::getServerStatus ( string $host [, int $port ] )
Returns the server status successfully. If the server is not started, 0 will be returned. Other numbers indicate that the server is started.
Parameters:
$host: The host that is listening for the connection
$port The port of the host that is listening for the connection, the default is 11211

3.Memcache::getStats – Returns the server’s Some running statistics
Syntax: array Memcache::getStats ([ string $type [, int $slabid [, int $limit ]]] )
Parameters:
$type indicates the requested return type: reset , malloc, maps, cachedump, slabs, items, sizes;
Used when the first parameter of $slabid is set to "cachedump".
$limit is used when the first parameter is set to "cachedump".

4.Memcache::getVersion – Returns the version information of the running Memcache
Syntax: string Memcache::getVersion (void)
Returns the version information of the server successfully, and returns false when it fails.

/****debug****/
1.memcache_debug – Control debugging function
Syntax: bool memcache_debug (bool $on_off)
If php is compiled using -enable- debug option, returns true, otherwise returns false
Parameters:
$on_off: true means turning on debugging, false means turning off debugging

2.Memcache::getExtendedStats – Get the running status of all processes in the process pool System statistics
Syntax: array Memcache::getExtendedStats ([ string $type [, int $slabid [, int $limit ]]] )
If successful, statistical information will be returned. If failed, false will be returned
Parameters:
$type indicates the type required to be returned: reset, malloc, maps, cachedump, slabs, items, sizes;
$slabid is used when the first parameter is set to "cachedump".
$limit is used when the first parameter is set to "cachedump".

/****compression****/
1.Memcache::setCompressThreshold – Compress data larger than a certain size
Syntax: bool Memcache::setCompressThreshold (int $threshold [, float $min_savings ] )
Returns TRUE if successful, returns FALSE if failed.
Parameters:
The setCompressThreshold method has two parameters. The first parameter indicates the critical point of processing data size, and the second parameter indicates the compression ratio. The default is 0.2.

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

How to use instanceof

##The difference and installation between LAMP, LNMP and LNAMP

The above is the detailed content of Introduction to the extension functions of the memcache class. For more information, please follow other related articles on the PHP Chinese website!

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 is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

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 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

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),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools