UFO ET IT

PHP의 생성자에 대한 __construct () 대 SameAsClassName ()

ufoet 2020. 11. 10. 22:40
반응형

PHP의 생성자에 대한 __construct () 대 SameAsClassName ()


__construct()PHP에서 생성자에 클래스 이름 대신 사용하면 어떤 이점이 있습니까?

예 ( __construct) :

class Foo {
    function __construct(){
        //do stuff
    }
}

예 (명명 됨) :

class Foo {
    function Foo(){
        //do stuff
    }
}

갖는 __construct방법 (제 1 예하면) PHP 5부터 사용 가능하다.

PHP 버전 4부터 버전 7까지 생성자 (두 번째 예)와 동일한 이름의 메서드를 사용할 수 있습니다.


저는 기즈모에 동의합니다. 장점은 클래스 이름을 변경해도 이름을 바꿀 필요가 없다는 것입니다. 마른.

마찬가지로 자식 클래스가있는 경우 다음을 호출 할 수 있습니다.

parent::__construct()

부모 생성자를 호출합니다. 트랙 아래에서 자식 클래스가 상속하는 클래스를 변경하면 부모에 대한 구성 호출을 변경할 필요가 없습니다.

작은 것 같지만 생성자 호출 이름을 부모 클래스로 변경하지 않으면 미묘한 (그다지 미묘하지 않은) 버그가 발생할 수 있습니다.

예를 들어, 상속인에 클래스를 삽입했지만 생성자 호출을 변경하는 것을 잊은 경우 부모 대신 조부모의 생성자를 호출 할 수 있습니다. 이로 인해 인식하기 어려울 수있는 바람직하지 않은 결과가 발생할 수 있습니다.

또한

PHP 5.3.3부터 네임 스페이스 클래스 이름의 마지막 요소와 동일한 이름을 가진 메서드는 더 이상 생성자로 처리되지 않습니다. 이 변경은 네임 스페이스가없는 클래스에는 영향을주지 않습니다.

출처 : http://php.net/manual/en/language.oop5.decon.php


__constructPHP5에서 도입되었습니다. 그것은 당신이 지금해야하는 방식입니다. 나는 그 자체 로 어떤 이점도 알지 못한다 .

PHP 매뉴얼에서 :

이전 버전과의 호환성을 위해 PHP 5가 주어진 클래스에 대한 __construct () 함수를 찾을 수 없으면 클래스 이름으로 구식 생성자 함수를 검색합니다. 사실상 호환성 문제가있는 유일한 경우는 클래스에 다른 의미론에 사용 된 __construct ()라는 메서드가있는 경우입니다.

PHP5를 사용 __construct하는 경우 PHP가 다른 곳에서 보이지 않도록 사용 하는 것이 좋습니다 .


__construct의 가장 큰 장점은 클래스 이름을 변경해도 생성자의 이름을 바꿀 필요가 없다는 것입니다.


오늘날 받아 들여지는 대답은 쓸모가 없습니다.

클래스 이름을 바꾸는 것은 나쁜 습관입니다. 새 버전으로 업그레이드 할 때마다 이름을 바꿀 내용과 이름을 기억해야합니다. 때로는 ( Reflection 또는 복잡한 의존성 구조를 사용하는 것과 같이 ) 근본적인 리팩토링 없이는 불가능할 수 있습니다. 그리고 이것은 여러분이 피하고 싶은 우발적 인 복잡성 입니다. 이것이 네임 스페이스 가 PHP에 도입 된 이유 입니다. Java, C ++ 또는 C #은를 사용하지 않고 __construct명명 된 생성자를 사용하며 문제가 없습니다.

PHP 5.3.3부터 네임 스페이스 클래스 이름 의 마지막 요소와 동일한 이름을 가진 메서드 는 더 이상 생성자로 처리되지 않습니다. 이 변경 은 네임 스페이스가없는 클래스에 영향을주지 않습니다 .

namespace Foo;
class Test {
  var $a = 3;

  function Test($a) {
    $this->a = $a;
  }

  function getA() {
    return $this->a;
  }
}

$test = new Test(4);
echo $test->getA(); // 3, Test is not a constructor, just ordinary function

Note that named constructors are not deprecated (PHP 5.5 today). However, you can't predict that your class won't be used in namespace, therefore __construct should be preffered.

Clarification about the bad practice mentioned above (for Dennis)

Somewhere in your code you could use ReflectionClass::getName(); when you rename the class, you need to remember where you used Reflection and check if the getName() result is still consistent in your app. The more you need to remember something specific, the more likely something is forgotten which results in bugs in the app.

The parents can't have control about all the classes in the world which depends on them. If allow_url_include is enabled, some other web might be using the class from your server, which may crash if you rename some class. It is even worse in compiled languages mentioned above: the library can be copied and bundled in other code.

There is no reason why to rename class:

  • if the class name conflicts, use namespaces
  • if the class responsibility shifts, derive some other class instead

In PHP classes in namespace, the method with the same name should be avoided anyway: intuitively it should produce an object created the class; if it does something else, why to give it the same name? It should be a constructor and nothing else. The main issue is that the behavior of such a method depends on namespace usage.

There is no issue with __construct constructors in PHP. But it wasn't the smartest idea to alter the named constructors.


The best advantage of using __contruct() instead of ClassName() is when extending classes. It is much easier to call parent::__construct() instead of parent::ClassName(), as it is reusable among classes and the parent can be changed easily.


In your example Foo::Foo is sometimes called a PHP 4 or old-style constructor because it comes from the days of PHP 4:

class Foo {
    // PHP 4 constructor
    function Foo(){
        //do stuff
    }
}

PHP 4 constructors will be deprecated but not removed in PHP 7. They will be no longer be considered as constructors in any situation in PHP 8. Future compatibility is definitely a big reason to not use this feature.


In PHP 5 the advantage would be that performance would be better. It will look for a constructor by the name of __construct first and if it doesn't find that, it will look for constructors by the name of className. So if it finds a constructor by the name __construct it does not need to search for a constructor by the name className.


Well it has been a few years since this question was asked, but I think I have to answer this one still, because things has changed and for readers in the future I want to keep the information up to date!


So in php-7 they will remove the option to create the constructor as a function with the same name as the class. If you still do it you will get a E_DEPRECATED.

You can read more about this proposal (the proposal is accepted) here: https://wiki.php.net/rfc/remove_php4_constructors

And a quote from there:

PHP 7 will emit E_DEPRECATED whenever a PHP 4 constructor is defined. When the method name matches the class name, the class is not in a namespace, and a PHP 5 constructor (__construct) is not present then an E_DEPRECATED will be emitted. PHP 8 will stop emitting E_DEPRECATED and the methods will not be recognized as constructors.

Also you won't get a E_STRICT in php-7 if you define a method with the same name as the class AND a __construct().

You can see this also here:

PHP 7 will also stop emitting E_STRICT when a method with the same name as the class is present as well as __construct.


So I would recommend you to use __construct(), since you will have less issues with this in the future.


Forward compatibility. There's always a chance that legacy code that's left in the language for backwards compatibility's sake will be removed in a future version.


If there is methods __construct and SameAsClassName method then __construct will be executed, SameAsClassName method will be skipped.


I think that the main reason is that is the language convention. You don't need to force a language to act like someone else.

I mean, in Objective-C you prefix the constructors with -init, for example. You can make your own constructor using your class name but why? Are ther some reason to use this schema instead of the language convention?

참고URL : https://stackoverflow.com/questions/217618/construct-vs-sameasclassname-for-constructor-in-php

반응형