Redeclare function (override)

What is the best method, to change the previously declared function into the new one?

for example, there is already declared:

function smth(){
echo 'aaa';
}

and i want that it displayed not aaa, but bbb

function smth(){
echo 'bbb';
}

but when i insert the new function (inside functions.php), i get error message

(Fatal error: Cannot redeclare **smth()** (previously declared in ... )

UPDATE – I have found a solution:

https://stackoverflow.com/a/8125517/2165415

Solutions Collecting From Web of "Redeclare function (override)"

PHP cannot redeclare functions. You will need to use some other approach, like filters or similar.

PHP doesn’t allow to redeclare functions. If you write the original function, there aare a lot of ways to allow you to write a more flexible functions.

Conditional on passed arguments and filter hook, are first that comes into my mind.

EX. 1:

function smth( $out = 'a' ){
  if ( $out === 'a' ) {
    echo 'aaa';
  } else {
    echo 'bbb';
  }
}

After that, first time call

smth();

and second time:

smth('b');

EX. 2

function smth(){
  echo apply_filters('my_smth_filter', 'aaa');
}

After that, first time call

smth();

and second time:

add_filter('my_smth_filter', function() {
  return 'bbb';
});
smth();

If the original function is not function of yours and it doesn’t provide any filter to change output and you absolutely need to change that function behaviour, then look at Patchwork, a PHP library that lets you redefine user-defined functions at runtime.
However use Patchwork with caution and only if absolutely necessary, because Patchwork is intended to be used for testing purpose, not on production.

I would suggest to use OOP approach, like:

class SomeClass
{
  public function aa()
  {
     echo 'aa';
  }
}

class SomeOtherClass extends SomeClass
{
   public function aa()
   {
      return 'bb';
   }
}

$a = new SomeClass();
$a->aa(); // outputs aa
$b = new SomeOtherClass();
$b->aa(); // outputs bb