search
HomeBackend DevelopmentPHP TutorialMobile app interface programming technology - learn to implement other features of the PHP class

  • Static static keyword

    static. In a class, the variables or methods marked by it do not belong to any object. Use "::" when accessing. And when calling self in a class, use "self::"
    For example:

<code><span><span><?php </span><span><span>class</span><span>Car</span> {</span><span>private</span><span>static</span><span>$speed</span> = <span>10</span>;

    <span>public</span><span><span>function</span><span>getSpeed</span><span>()</span> {</span><span>return</span><span>self</span>::<span>$speed</span>;
    }

    <span>//在这里定义一个静态方法,实现速度累加10</span><span>public</span><span>static</span><span><span>function</span><span>speedUp</span><span>()</span>
    {</span><span>return</span><span>self</span>::<span>$speed</span> += <span>10</span>;
    }
}

<span>$car</span> = <span>new</span> Car();
Car::speedUp();  <span>//调用静态方法加速</span><span>echo</span><span>$car</span>->getSpeed();  <span>//调用共有方法输出当前的速度值</span></span></span></code>

Static methods can also be called dynamically through variables.

<code><span>$func</span> = <span>'getSpeed'</span>;
<span>$className</span> = <span>'Car'</span>;
<span>echo</span><span>$className</span>::<span>$func</span>();  <span>//动态调用静态方法</span></code>
  • Access control

Access control is implemented through the keywords public, protected and private. Class members defined as public can be accessed from anywhere. Class members defined as protected can be accessed by itself and its subclasses and parent classes. Class members defined as private can only be accessed by the class in which they are defined.

Class attributes must be defined as one of public, protected, and private.

Methods in a class can be defined as public, private or protected. If these keywords are not set, the method defaults to public.

If the constructor is defined as a private method, the object is not allowed to be instantiated directly. At this time, it is generally instantiated through static methods. This method is often used in design patterns to control the creation of objects, such as singleton mode. Only one globally unique object is allowed.

<code><span><span>class</span><span>Car</span> {</span><span>private</span><span><span>function</span><span>__construct</span><span>()</span> {</span><span>echo</span><span>'object create'</span>;
    }

    <span>private</span><span>static</span><span>$_object</span> = <span>null</span>;
    <span>public</span><span>static</span><span><span>function</span><span>getInstance</span><span>()</span> {</span><span>if</span> (<span>empty</span>(<span>self</span>::<span>$_object</span>)) {
            <span>self</span>::<span>$_object</span> = <span>new</span> Car(); 
            <span>//内部方法可以调用私有方法,因此这里可以创建对象</span>
        }
        <span>return</span><span>self</span>::<span>$_object</span>;
    }
}
<span>//$car = new Car(); //这里不允许直接实例化对象</span><span>$car</span> = Car::getInstance(); <span>//通过静态方法来获得一个实例</span></code>
  • Inheritance
<code><span><span><?php </span><span><span>class</span><span>Car</span> {</span><span>public</span><span>$speed</span> = <span>0</span>; <span>//汽车的起始速度是0</span><span>public</span><span><span>function</span><span>speedUp</span><span>()</span> {</span><span>$this</span>->speed += <span>10</span>;
        <span>return</span><span>$this</span>->speed;
    }
}
<span>//定义继承于Car的Truck类</span><span><span>class</span><span>Truck</span><span>extends</span><span>Car</span>{</span><span>public</span><span><span>function</span><span>speedUp</span><span>()</span> {</span><span>$this</span>->speed = <span>parent</span>::speedUp() + <span>50</span>;
    }
}

<span>$car</span> = <span>new</span> Truck();
<span>$car</span>->speedUp();
<span>echo</span><span>$car</span>->speed;</span></span></code>
  • Overloading

Overloading in PHP refers to the dynamic creation of properties and methods, which is achieved through magic methods. The overloading of attributes uses __set, __get, __isset, and __unset to implement assignment, reading, determining whether the attribute is set, and destroying the attribute if it does not exist, respectively.

<code><span><span>class</span><span>Car</span> {</span><span>private</span><span>$ary</span> = <span>array</span>();

    <span>public</span><span><span>function</span><span>__set</span><span>(<span>$key</span>, <span>$val</span>)</span> {</span><span>$this</span>->ary[<span>$key</span>] = <span>$val</span>;
    }

    <span>public</span><span><span>function</span><span>__get</span><span>(<span>$key</span>)</span> {</span><span>if</span> (<span>isset</span>(<span>$this</span>->ary[<span>$key</span>])) {
            <span>return</span><span>$this</span>->ary[<span>$key</span>];
        }
        <span>return</span><span>null</span>;
    }

    <span>public</span><span><span>function</span><span>__isset</span><span>(<span>$key</span>)</span> {</span><span>if</span> (<span>isset</span>(<span>$this</span>->ary[<span>$key</span>])) {
            <span>return</span><span>true</span>;
        }
        <span>return</span><span>false</span>;
    }

    <span>public</span><span><span>function</span><span>__unset</span><span>(<span>$key</span>)</span> {</span><span>unset</span>(<span>$this</span>->ary[<span>$key</span>]);
    }
}
<span>$car</span> = <span>new</span> Car();
<span>$car</span>->name = <span>'汽车'</span>;  <span>//name属性动态创建并赋值</span><span>echo</span><span>$car</span>->name;
</code>

Method overloading is implemented through __call. When a method that does not exist is called, the __call method will be called as a parameter. When a static method that does not exist is called, the __callStatic overload will be used.

<code>lass Car {
    <span>public</span><span>$speed</span> = <span>0</span>;

    <span>public</span><span><span>function</span><span>__call</span><span>(<span>$name</span>, <span>$args</span>)</span> {</span><span>if</span> (<span>$name</span> == <span>'speedUp'</span>) {
            <span>$this</span>->speed += <span>10</span>;
        }
    }
}
<span>$car</span> = <span>new</span> Car();
<span>$car</span>->speedUp(); <span>//调用不存在的方法会使用重载</span><span>echo</span><span>$car</span>->speed;</code>
  • Class object comparison

Object comparison, when all attributes of two instances of the same class are equal, you can use the comparison operator "==" to make a judgment. When you need to judge whether two variables are the same When referencing an object, you can use the equality operator "===" to make a judgment.

<code><span><span>class</span><span>Car</span> {</span>
}
<span>$a</span> = <span>new</span> Car();
<span>$b</span> = <span>new</span> Car();
<span>if</span> (<span>$a</span> == <span>$b</span>) <span>echo</span><span>'=='</span>;   <span>//true</span><span>if</span> (<span>$a</span> === <span>$b</span>) <span>echo</span><span>'==='</span>; <span>//false</span></code>

Object copying. In some special cases, you can copy an object through the keyword clone. At this time, the __clone method will be called, and the value of the attribute is set through this magic method.

<code><span><span>class</span><span>Car</span> {</span><span>public</span><span>$name</span> = <span>'car'</span>;

    <span>public</span><span><span>function</span><span>__clone</span><span>()</span> {</span><span>$obj</span> = <span>new</span> Car();
        <span>$obj</span>->name = <span>$this</span>->name;
    }
}
<span>$a</span> = <span>new</span> Car();
<span>$a</span>->name = <span>'new car'</span>;
<span>$b</span> = <span>clone</span><span>$a</span>;
var_dump(<span>$b</span>);
</code>

Object serialization, you can serialize the object into a string through the serialize method, which is used to store or transfer data, and then deserialize the string into an object for use through unserialize when needed.

<code><span><span>class</span><span>Car</span> {</span><span>public</span><span>$name</span> = <span>'car'</span>;
}
<span>$a</span> = <span>new</span> Car();
<span>$str</span> = serialize(<span>$a</span>); <span>//对象序列化成字符串</span><span>echo</span><span>$str</span>.<span>'<br>'</span>;
<span>$b</span> = unserialize(<span>$str</span>); <span>//反序列化为对象</span>
var_dump(<span>$b</span>);
</code>

Copyright Statement: This article is the original article of the blogger and may not be reproduced without the permission of the blogger.

The above introduces the mobile app interface programming technology - learning to implement other features of the PHP class, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.

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

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment