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);
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1ea99ad-47d33.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1ea99ad-47d33.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?