search
HomeBackend DevelopmentPHP TutorialSummary of PHP object-oriented basic knowledge_PHP tutorial
Summary of PHP object-oriented basic knowledge_PHP tutorialJul 13, 2016 pm 05:52 PM
phpbutbasic knowledgeobjectengineerSummarizeidealoftest questionsForinterview

I recently participated in several interviews with PHP engineers, but my answers to the written test questions were not satisfactory. When I came back, I summarized the reason for the failure. It was because I did not read the PHP manual. PHP basic interview questions from several companies can be found in the PHP manual. Hey, now I know that the best interview guide is the PHP manual.
​​​​​ The following are excerpts from some PHP object-oriented basics, taken from the PHP5.1 manual.
1. The variable members of a class are called "properties", or "fields" or "features", and are collectively referred to as "properties" in this document.
2. The variables in the attributes can be initialized, but the initialized value must be a constant. The constant here means that the php script is a constant during the compilation stage, not
Constants that are evaluated during the runtime phase after the compile phase.
3. In the member method of the class, you can access the properties and methods of the class through $this->property (property is the property name), but
To access static properties of a class or within a static method, use self::$property instead.
4. You can use the pseudo variable $this in the non-static method of the class. This pseudo variable is the reference to the instantiated object that calls the method
5. The value of a constant must be a fixed value, no modification is allowed, and it cannot be the result of a variable, class attribute or other operation (such as a function call).
class MyClass
{
const constant = 'constant value';
Function showConstant() {
echo self::constant . "n";
}
}
echo MyClass::constant . "n";
$n=new MyClass();
$n->showConstant();
?>
6. The constructor class will call this method first every time it creates an object, so it is very suitable to do some initialization work before using the object.
If a constructor is defined in a subclass, the constructor of its parent class will not be implicitly called. To execute the constructor of the parent class, you need to
in the constructor of the subclass Call parent::__construct().
7. The destructor is executed when all references to an object are deleted or when the object is explicitly destroyed.
The destructor of the parent class is not implicitly called by the engine. To execute the destructor of the parent class, you must explicitly call
in the destructor body of the child class parent::__destruct().
The destructor is called when the script is closed, after all header information has been emitted.
Attempting to throw an exception in the destructor results in a fatal error.
8. When extending a class, the subclass will inherit all the public and protected methods of the parent class. But the methods of the subclass will override the methods of the parent class.
9. Range resolution operator (::), which can be used to access static members, methods and constants
When accessing these static members, methods, and constants from outside the class, the class name must be used.
The two special keywords self and parent are used to access members or methods inside the class.
10. When a subclass overrides a method in its parent class, PHP will no longer execute the overridden methods in the parent class until these methods are called in the subclass. This
This mechanism also works with constructors and destructors, overloaded and magic functions.
11. Static variables and methods
By declaring a class member or method as static, you can access it directly without instantiating the class. Static members cannot be accessed through an object (static methods
except).
Since static methods do not require an object to be called, the pseudo variable $this is not available in static methods.
Static properties cannot be accessed by objects through the -> operator.
Calling a non-static method using the :: method will result in an E_STRICT level error.
Like all other PHP static variables, static properties can only be initialized to a character value or a constant, not expressions. So you can
You can initialize a static property to an integer or array, but it cannot point to another variable or function return value, nor to an object.

12. If "visibility" is not specified, properties and methods default to public.
13.Abstract class
Abstract classes cannot be instantiated directly; you must first inherit from the abstract class and then instantiate the subclass. An abstract class must contain at least one abstract method. if
Class methods are declared abstract, so they cannot include concrete functional implementations.
When inheriting an abstract class, the subclass must implement all abstract methods in the abstract class; in addition, the visibility of these methods must be the same as in the abstract class (
or looser). If an abstract method in an abstract class is declared protected, then the method implemented in the subclass should be declared protected
Or public, but cannot be defined as private.
Application example:
abstract class AbstractClass
{
// Force subclasses to define these methods
abstract protected function getValue();
abstract protected function prefixValue($prefix);
// Ordinary methods (non-abstract methods)
Public function printOut() {
               print $this->getValue() . "n";
}
}
class ConcreteClass1 extends AbstractClass
{
protected function getValue() {
          return "ConcreteClass1";
}
Public function prefixValue($prefix) {
           return "{$prefix}ConcreteClass1";
}
}
14. Using an interface, you can specify which methods a class must implement, but you do not need to define the specific content of these methods.
We can define an interface through interface, just like defining a standard class, but all methods defined in it are empty.
All methods defined in an interface must be public, which is a characteristic of the interface.
To implement an interface, use the implements operator. The class must implement all methods defined in the interface, otherwise a fatal error will be reported.
If you want to implement multiple interfaces, you can use commas to separate the names of multiple interfaces.
When implementing multiple interfaces, methods in the interfaces cannot have the same name.
Interfaces can also be inherited, using the extends operator.
Constants can also be defined in interfaces. Interface constants and class constants are used exactly the same. They are all fixed values ​​and cannot be modified by subclasses or subinterfaces.
Application example:
//Interface definition
interface iTemplate
{
Public function setVariable($name, $var);
Public function getHtml($template);
}
//Use interface
class Template implements iTemplate
{
Private $vars = array();

Public function setVariable($name, $var)
{
            $this->vars[$name] = $var;
}

Public function getHtml($template)
{
foreach($this->vars as $name => $value) {
$template = str_replace('{' . $name . '}', $value, $template);
}

          return $template;
}
}
15.PHP5 provides a function to iterate objects. Just like using an array, you can traverse the properties in the object through foreach.
By default, external iteration can only get the values ​​of externally visible properties.
Application example:
class MyClass
{
Public $var1 = 'value 1';
Public $var2 = 'value 2';
Public $var3 = 'value 3';
protected $protected = 'protected var';
private $private = 'private var';
Function iterateVisible() {
echo "MyClass::iterateVisible:n";
foreach($this as $key => $value) {
​​​​​​print "$key => }
}
}
$class = new MyClass();
foreach($class as $key => $value) {
Print "$key => $valuen";
}
echo "n";

$class->iterateVisible();
?>
16. Design Patterns
The Factory pattern allows you to instantiate objects while your code is executing. It is called the factory pattern because it is responsible for "producing" objects. Factory
The parameter of the method is the class name corresponding to the object you want to generate.
Singleton pattern is used to generate a unique object for a class. The most commonly used place is database connection. Use singleton pattern to generate a
After an object is created, the object can be used by many other objects.
Application example:
class Example
{
//Save the class instance in this attribute
Private static $instance;
 
                 // The constructor is declared as private to prevent direct creation of objects
Private function __construct()
{
echo 'I am constructed';
}
// singleton method
Public static function singleton()
{
If (!isset(self::$instance)) {
               $c = __CLASS__;
                self::$instance = new $c;
}
          return self::$instance;
}
 
// Ordinary methods in Example class
Public function bark()
{
echo 'Woof!';
}
// Prevent users from copying object instances
Public function __clone()
{
         trigger_error('Clone is not allowed.', E_USER_ERROR);
}
}
?>

In this way we can get a unique object of Example class.

// This way of writing will be wrong because the constructor is declared as private
$test = new Example;
//The following will get the singleton object of the Example class
$test = Example::singleton();
$test->bark();
// Copying the object will result in an E_USER_ERROR.
$test_clone = clone $test;
?>
17.PHP 5 adds a new final keyword. If a method in the parent class is declared final, the subclass cannot override the method; if a class is declared final If declared final, it cannot be inherited.
18. Object copying can be completed through the clone keyword (if the __clone() method exists in the object, it will be called first). __clone()
in object Methods cannot be called directly.
$copy_of_object = clone $object;
When an object is copied, PHP5 will perform a "shallow copy" of all properties of the object. All references in attributes are still not
Change, pointing to the original variable. If the __clone() method is defined, the __clone() method in the newly created object (the object generated by copying) will be called
can be used to modify the value of a property (if necessary).

19. Object comparison
When using the comparison operator (==) to compare two object variables, the comparison principle is: if the attributes and attribute values ​​of the two objects are equal, and the two objects
are instances of the same class, then the two object variables are equal. www.2cto.com
And if you use the equality operator (===), the two object variables must point to the same instance of a certain class (that is, the same object).
20. Objects and references
PHP references are aliases, that is, two different variable names point to the same content. In PHP5, an object variable no longer holds the value of the entire object.
Just save an identifier to access the real object content. When an object is passed as a parameter, returned as a result, or assigned to another variable, another
The outer variable has no reference relationship with the original one, but they both store copies of the same identifier, which points to the real
of the same object. Content
Author: JL_liuning


http://www.bkjia.com/PHPjc/478097.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/478097.htmlTechArticleI recently participated in several PHP engineer interviews, but my answers to the written test questions were not satisfactory. I came back to summarize the failure. The reason is that I didn't read the PHP manual. PHP basic interview questions from several companies are available...
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
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace(" ","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

php怎么判断有没有小数点php怎么判断有没有小数点Apr 20, 2022 pm 08:12 PM

php判断有没有小数点的方法:1、使用“strpos(数字字符串,'.')”语法,如果返回小数点在字符串中第一次出现的位置,则有小数点;2、使用“strrpos(数字字符串,'.')”语句,如果返回小数点在字符串中最后一次出现的位置,则有。

php怎么读取字符串后几个字符php怎么读取字符串后几个字符Apr 22, 2022 pm 08:31 PM

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)