Home Backend Development PHP Tutorial Detailed explanation of PHP class and method keyword tutorials

Detailed explanation of PHP class and method keyword tutorials

May 17, 2018 pm 01:49 PM
php Keywords Tutorial

The following is a tutorial on PHP classes and method keywords that I have compiled for you. Interested students can take a look.

1. final
If we don’t want a class to be inherited, we use final to modify the class. This class will not be inherited.
final---used before classes and methods.
Final class---cannot be inherited.
Final method---cannot be overridden.
2. Public means global, and can be accessed by subclasses inside and outside the class; private means private, and can only be used within this class; protected means protected, and can only be accessed by this class, subclasses, or parent classes;
3. This is a pointer to the current object (can be regarded as a pointer in C), self is a pointer to the current class, parent is a pointer to the parent class
self: When variables and methods are set to static, If you use self
4 or static
to declare a class member or method as static in this class, you can directly access it without instantiating the class. You cannot access the static members (except static methods) through an object. Static members belong to the class and do not belong to any object instance, but object instances of the class can be shared.
Then let’s take a look at the difference between using $object->… and using class::…:
1. When using $object->…, you need to execute the constructorCreate objects;
2. Use class::... to call static methods/variables, without executing the constructor to create objects;
3. Use class::... to call non-static methods/variables, also There is no need to execute a constructor to create an object.
5. abstract
1. Abstract classabstract class
1. An abstract class refers to a class with the abstract keyword added before class and an abstract method (abstract keyword added before the class method function keyword).
2 . Abstract classes cannot be instantiated directly. The abstract class only defines (or partially implements) the methods required by the subclass. Subclasses can make an abstract class concrete by inheriting it and by implementing all the abstract methods in the abstract class.
3. If a subclass needs to be instantiated, it must implement all abstract methods in the abstract class. If the subclass does not implement all abstract methods in the abstract class, then the subclass is also an abstract class and must be preceded by the abstract keyword in class and cannot be instantiated.
6、interface interface
1. Abstract classes provide standards for concrete implementation, while interfaces are pure templates. Interfaces only define functions, not implementation content. Interfaces are declared with the keyword interface.
2 . Interface is completely abstract. It can only declare methods, and only public methods. It cannot declare private and protected methods, cannot define method bodies, and cannot declare instance variables. However, interfaces can declare constant variables. But placing constant variables in an interface violates its purpose of existing as an interface, and also confuses the different values ​​of interfaces and classes. If you really need it, you can put it in the corresponding abstract class or Class.
7, instanceof
Another new member of PHP5 is the instdnceof keyword. Use this keyword to determine whether an object is an instance of a class, a subclass of a class, or implements a specific interface, and perform corresponding operations. In some cases, we want to determine whether a class is of a specific type, or implements a specific interface. instanceofoperator is very suitable for this task. The instanceof operator checks three things: whether the instance is of a specific type, whether the instance inherits from a specific type, and whether the instance or any of its ancestor classes implements a specific interface. For example, suppose you want to know whether an object named manager is an instance of class Employee:

$manager = new Employee();
if ($manager instanceof Employee)
  echo "Yes";
有两点值得注意。首先,类名没有任何定界符(引号)。使用定界符将导致
语法错误
。其次,如果比较失败,脚本将退出执行。instanceof关键字在同时处理多个对象时特别有用。例如,你可能要重复地调用某个函数,但希望根据对象类型调整函数的行为。可以使用case语句和instanceof关键字来实现这个目标。
class test{}
class test{}
class testChilern 
Extends
 test{}
$a = new test();
$m = new test();
$i = ($m instanceof test);
if($i)
  echo &#39;$m是类test的实例!<br />&#39;; // get this value
switch ($a instanceof test){
  case true :
    echo &#39;YES<br />&#39;;
    break;
  case false :
    echo &#39;No<br />&#39;; //get this value
    break;
}
$d=new testChilern();
if($d instanceof test)echo &#39;$d是类test的子类!<br />&#39;; // get this value
Copy after login

What is the role of instanceof in php
Function: (1) Determine whether an object is of a certain class Instance, (2) Determine whether an object implements a certain interface.
First usage:

<?php
$obj = new A();
if ($obj instanceof A) {
  echo &#39;A&#39;;
}
Copy after login

Second usage:

<?php
interface ExampleInterface
{
   public function interfaceMethod();
 }
 class ExampleClass implements ExampleInterface
{
   public function interfaceMethod()
   {
     return &#39;Hello World!&#39;;
   }
 }
$exampleInstance = new ExampleClass();
 if($exampleInstance instanceof ExampleInterface){
   echo &#39;Yes, it is&#39;;
 }else{
   echo &#39;No, it is not&#39;;
} 
?>
Copy after login

Output result: Yes, it is
In addition, please pay attention to instanceof and is_subclass_of (), please look at the code:

<?php
class Foo {
   public $foobar = &#39;Foo&#39;;
   public function test() {
     echo $this->foobar . "\n";
   }
 }
 class Bar extends Foo {
   public $foobar = &#39;Bar&#39;;
 }
$a = new Foo();
$b = new Bar();
echo "use of test() method\n";
$a->test();
$b->test();
echo "instanceof Foo\n";
var_dump($a instanceof Foo); // TRUE
var_dump($b instanceof Foo); // TRUE
echo "instanceof Bar\n";
var_dump($a instanceof Bar); // FALSE
var_dump($b instanceof Bar); // TRUE
echo "subclass of Foo\n";
var_dump(is_subclass_of($a, &#39;Foo&#39;)); // FALSE
var_dump(is_subclass_of($b, &#39;Foo&#39;)); // TRUE
echo "subclass of Bar\n";
var_dump(is_subclass_of($a, &#39;Bar&#39;)); // FALSE
var_dump(is_subclass_of($b, &#39;Bar&#39;)); // FALSE
?>
 输出结果(PHP 5.4.4):
 use of test() method
 Foo
 Bar
 instanceof Foo
 bool(true)
 bool(true)
 instanceof Bar
 bool(false)
 bool(true)
 subclass of Foo
 bool(false)
 bool(true)
 subclass of Bar
 bool(false)
Copy after login

The above is a tutorial I compiled to explain PHP classes and method keywords. I hope it will be helpful to you in the future.

Related articles:

Specific usage methods of namespace and use

PHP closure function() use() Detailed usage guide

Detailed usage guide for PHP namespace namespace and import use


The above is the detailed content of Detailed explanation of PHP class and method keyword tutorials. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles