How do you add a method to a class in a php file with code?

for example, there is now a file with the content

class Foo
{
    public function __construct() {
    
    }
    
    public function a() {}
}

I want to change the contents of the file to

class Foo
{
    protected $var;

    public function __construct() {
    
    }
    
    public function a() {}
    public function b() {}
}
How can

be implemented in code? How do you navigate to the location where you want to add the string?

Php
Feb.28,2021

normally I would recommend inheritance.

but it seems that the subject really wants to add methods to the class in the way of character editing, which is complicated, at least I don't know that there are ready-made libraries or tools to support this. I suggest that the subject write a simple parsing tool to do it from the entry of the document structure, such as finding the entry (in line with ~ class (\ w +) ~ ) and parsing it line by line.


class Foo
{
    public function __construct() {
    
    }
    
    public function a() {}
    //add code area
}
$a = file_get_contents('a.php');
$addCode = 'public function b() {}';
$a = str_replace('//add code area',$addCode."\n\t//add code area",$a);
file_put_contents('a.php',$a);
Menu