Home > Backend Development > PHP Problem > What is the way to call a class with string name in PHP

What is the way to call a class with string name in PHP

coldplay.xixi
Release: 2023-03-08 10:14:01
Original
3049 people have browsed it

PHP uses the string name to call the class method: 1. Use the [call_user_func] method, the code is [call_user_func(array($game, 'Play'), 1)]; 2. Use the Play method, the code It is [$game->{'Play'}(2)].

What is the way to call a class with string name in PHP

The operating environment of this tutorial: Windows 7 system, PHP version 5.6, DELL G3 computer. This method is suitable for all brands of computers.

PHP uses the string name to call the method of the class:

You can use the call_user_func method and the Play method

The specific code is shown below:

<?php
class Game {
    function Play($id) {
        echo "Playing game $id\n";
    }
}
$game = new Game();
//方法1,使用call_user_func
call_user_func(array($game, &#39;Play&#39;), 1);
//方法2
$game->{&#39;Play&#39;}(2);
//或者
$method = &#39;Play&#39;;
$game->$method(3);
Copy after login

Related video recommendations: PHP programming from entry to proficiency

The above is the detailed content of What is the way to call a class with string name in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template