IT Share you

PHP에서 함수를 덮어 쓸 수 있습니까?

shareyou 2020. 11. 25. 21:39
반응형

PHP에서 함수를 덮어 쓸 수 있습니까?


다음 과 같은 함수 선언 할 수 있습니까 ?

function ihatefooexamples(){
  return "boo-foo!";
};

그런 다음 다소 재 선언 합니다.

if ($_GET['foolevel'] == 10){
  function ihatefooexamples(){
    return "really boo-foo";
  };
};

그런 식으로 함수를 덮어 쓸 수 있습니까?

어쨌든?


편집하다

이 답변이 원래 질문을 직접 다루지 않는다는 의견을 다루기 위해. Google 검색에서 여기로 온 경우 여기에서 시작하세요.

실제로 청구서에 맞는 override_function 이라는 함수가 있습니다 . 그러나이 함수가 The Advanced PHP Debugger 확장 일부 override_function()이기 때문에 프로덕션 용도로 사용할 인수를 만들기가 어렵습니다 . 따라서 "아니오"라고 말하고 원래 질문자가 염두에 둔 의도로 함수를 덮어 쓸 수 없습니다.

원래 답변

여기서 OOP, 특히 다형성을 활용해야합니다.

interface Fooable
{
    public function ihatefooexamples();
}

class Foo implements Fooable
{
    public function ihatefooexamples()
    {
        return "boo-foo!";
    }
}

class FooBar implements Fooable
{
    public function ihatefooexamples()
    {
        return "really boo-foo";
    }
}

$foo = new Foo();

if (10 == $_GET['foolevel']) {
    $foo = new FooBar();
}

echo $foo->ihatefooexamples();

네임 스페이스의 Monkey 패치 PHP> = 5.3

인터프리터를 수정하는 것보다 덜 회피적인 방법은 원숭이 패치입니다.

몽키 패치는 실제 구현을 유사한 "패치"로 대체하는 기술입니다.

닌자 기술

PHP 닌자처럼 원숭이 패치를하기 전에 먼저 PHP 네임 스페이스를 이해해야합니다.

PHP 5.3부터 우리는 언뜻보기에 자바 패키지와 같은 것으로 표시 할 수있는 네임 스페이스를 도입했지만, 완전히 동일하지는 않습니다. PHP에서 네임 스페이스는 특히 함수와 상수에 대해 포커스 계층을 만들어 범위를 캡슐화하는 방법입니다. 이 주제에서는 전역 함수로의 대체 가 설명하는 것을 목표로합니다.

당신이 경우 함수를 호출 할 때 네임 스페이스를 제공하지 않는 것이 첫 번째 함수는 그 앞에 둔 네임 스페이스와 실행하는 내에서 선언 발견 할 때까지, 현재의 이름 공간에있는 PHP 최초의 외모는 계층 구조 아래로 이동합니다. 예를 들어 PHP 가하는 일 print_r();에서 호출하는 경우 먼저 호출 namespace My\Awesome\Namespace;함수를 My\Awesome\Namespace\print_r();찾은 My\Awesome\print_r();다음 My\print_r();전역 네임 스페이스에서 PHP 내장 함수를 찾을 때까지 찾습니다 \print_r();.

function print_r($object) {}해당 이름을 가진 함수가 이미 존재하기 때문에 이름 충돌이 발생하기 때문에 전역 네임 스페이스에서을 정의 할 수 없습니다 .

다음과 같은 사람에게 치명적인 오류가 발생할 수 있습니다.

Fatal error: Cannot redeclare print_r()

그러나 네임 스페이스 범위 내에서 그렇게하는 것을 막을 수있는 것은 없습니다.

원숭이 패치

여러 print_r();호출을 사용하는 스크립트가 있다고 가정 해 보겠습니다 .

예:

<?php
     print_r($some_object);
     // do some stuff
     print_r($another_object);
     // do some other stuff
     print_r($data_object);
     // do more stuff
     print_r($debug_object);

그러나 나중에 마음이 바뀌고 출력을 <pre></pre>대신 태그로 묶기를 원합니다 . 당신에게 일어난 적이 있습니까?

가기 전에 모든 호출을 변경하여 print_r();대신 원숭이 패치 고려하십시오.

예:

<?php
    namespace MyNamespace {
        function print_r($object) 
        {
            echo "<pre>", \print_r($object, true), "</pre>"; 
        }

        print_r($some_object);
        // do some stuff
        print_r($another_object);
        // do some other stuff
        print_r($data_object);
        // do more stuff
        print_r($debug_object);
    }

이제 스크립트가 MyNamespace\print_r();전역 대신 사용 됩니다.\print_r();

모의 단위 테스트에 적합합니다.

nJoy!


override_function기능을 재정의하려면 살펴보십시오 .

override_function — 내장 함수를 재정의합니다.

예:

override_function('test', '$a,$b', 'echo "DOING TEST"; return $a * $b;');

짧은 대답은 '아니요'입니다. PHP 함수 범위에 있으면 함수를 덮어 쓸 수 없습니다.

익명의 함수를 사용하는 최선의 방법

$ihatefooexamples = function()
{
  return "boo-foo!";
}

//...
unset($ihatefooexamples);
$ihatefooexamples = function()
{
   return "really boo-foo";
}

http://php.net/manual/en/functions.anonymous.php


You cannot redeclare any functions in PHP. You can, however, override them. Check out overriding functions as well as renaming functions in order to save the function you're overriding if you want.

So, keep in mind that when you override a function, you lose it. You may want to consider keeping it, but in a different name. Just saying.

Also, if these are functions in classes that you're wanting to override, you would just need to create a subclass and redeclare the function in your class without having to do rename_function and override_function.

Example:

rename_function('mysql_connect', 'original_mysql_connect' );
override_function('mysql_connect', '$a,$b', 'echo "DOING MY FUNCTION INSTEAD"; return $a * $b;');

I would include all functions of one case in an include file, and the others in another include.

For instance simple.inc would contain function boofoo() { simple } and really.inc would contain function boofoo() { really }

It helps the readability / maintenance of your program, having all functions of the same kind in the same inc.

Then at the top of your main module

  if ($_GET['foolevel'] == 10) {
    include "really.inc";
  }
  else {
    include "simple.inc";
  }

You could use the PECL extension

but that is bad practise in my opinion. You are using functions, but check out the Decorator design pattern. Can borrow the basic idea from it.


No this will be a problem. PHP Variable Functions


A solution for the related case where you have an include file A that you can edit and want to override some of its functions in an include file B (or the main file):

Main File:

<?php
$Override=true; // An argument used in A.php
include ("A.php");
include ("B.php");
F1();
?>

Include File A:

<?php
if (!@$Override) {
   function F1 () {echo "This is F1() in A";}
}
?>

Include File B:

<?php
   function F1 () {echo "This is F1() in B";}
?>

Browsing to the main file displays "This is F1() in B".


Depending on situation where you need this, maybe you can use anonymous functions like this:

$greet = function($name)
{
    echo('Hello ' . $name);
};

$greet('World');

...then you can set new function to the given variable any time

참고URL : https://stackoverflow.com/questions/3620659/is-it-possible-to-overwrite-a-function-in-php

반응형