development

__construct 함수는 무엇입니까?

big-blog 2020. 5. 13. 20:30
반응형

__construct 함수는 무엇입니까?


나는 __construct수업에 많은 주목을 받았다 . 웹을 약간 읽고 서핑을했지만 이해할 수있는 설명을 찾을 수 없었습니다. 방금 OOP로 시작하고 있습니다.

누군가 나에게 그것이 무엇인지에 대한 일반적인 아이디어를 제공하고 PHP와 함께 어떻게 사용되는지에 대한 간단한 예를 줄 수 있는지 궁금합니다.


__constructPHP5에 도입되었으며 잘 생성자를 정의하는 올바른 방법입니다 (PHP4에서는 생성자의 클래스 이름을 사용했습니다). 클래스에서 생성자를 정의 할 필요는 없지만 객체 생성시 매개 변수를 전달하려면 생성자가 필요합니다.

예를 들면 다음과 같습니다.

class Database {
  protected $userName;
  protected $password;
  protected $dbName;

  public function __construct ( $UserName, $Password, $DbName ) {
    $this->userName = $UserName;
    $this->password = $Password;
    $this->dbName = $DbName;
  }
}

// and you would use this as:
$db = new Database ( 'user_name', 'password', 'database_name' );

다른 모든 것은 PHP 매뉴얼에 설명되어 있습니다 : 여기를 클릭하십시오


__construct()생성자 의 메서드 이름입니다 . 생성자는 생성 된 객체에서 호출되며 초기화 코드 등을 넣을 수있는 좋은 장소입니다.

class Person {

    public function __construct() {
        // Code called for each new Person we create
    }

}

$person = new Person();

생성자는 객체를 만들 때 전달되는 일반적인 방식으로 매개 변수를 사용할 수 있습니다. 예 :

class Person {

    public $name = '';

    public function __construct( $name ) {
        $this->name = $name;
    }

}

$person = new Person( "Joe" );
echo $person->name;

다른 언어 (예 : Java)와 달리 PHP는 생성자 오버로드를 지원하지 않습니다 (즉, 다른 매개 변수를 허용하는 여러 생성자가 있음). 정적 메소드를 사용하여이 효과를 얻을 수 있습니다.

참고 : 나는 (이 글을 쓸 당시) 수락 된 답변의 로그에서 이것을 찾았습니다.


생성자를 선언하는 또 다른 방법입니다. 예를 들어 클래스 이름을 사용할 수도 있습니다.

class Cat
{
    function Cat()
    {
        echo 'meow';
    }
}

class Cat
{
    function __construct()
    {
        echo 'meow';
    }
}

동등합니다. 클래스의 새 인스턴스가 작성 될 때마다 호출되며,이 경우 다음 행으로 호출됩니다.

$cat = new Cat();

I think this is important to the understanding of the purpose of the constructor.
Even after reading the responses here it took me a few minutes to realise and here is the reason.
I have gotten into a habit of explicitly coding everything that is initiated or occurs. In other words this would be my cat class and how I would call it.

class_cat.php

class cat {
    function speak() {
        return "meow";  
    }
}

somepage.php

include('class_cat.php');
mycat = new cat;
$speak = cat->speak();
echo $speak;

Where in @Logan Serman's given "class cat" examples it is assumed that every time you create a new object of class "cat" you want the cat to "meow" rather than waiting for you to call the function to make it meow.

In this way my mind was thinking explicitly where the constructor method uses implicity and this made it hard to understand at first.


The constructor is a method which is automatically called on class instantiation. Which means the contents of a constructor are processed without separate method calls. The contents of a the class keyword parenthesis are passed to the constructor method.


I Hope this Help:

<?php
    // The code below creates the class
    class Person {
        // Creating some properties (variables tied to an object)
        public $isAlive = true;
        public $firstname;
        public $lastname;
        public $age;

        // Assigning the values
        public function __construct($firstname, $lastname, $age) {
          $this->firstname = $firstname;
          $this->lastname = $lastname;
          $this->age = $age;
        }

        // Creating a method (function tied to an object)
        public function greet() {
          return "Hello, my name is " . $this->firstname . " " . $this->lastname . ". Nice to meet you! :-)";
        }
      }

    // Creating a new person called "boring 12345", who is 12345 years old ;-)
    $me = new Person('boring', '12345', 12345);

    // Printing out, what the greet method returns
    echo $me->greet(); 
    ?>

For More Information You need to Go to codecademy.com


The __construct method is used to pass in parameters when you first create an object--this is called 'defining a constructor method', and is a common thing to do.

However, constructors are optional--so if you don't want to pass any parameters at object construction time, you don't need it.

So:

// Create a new class, and include a __construct method
class Task {

    public $title;
    public $description;

    public function __construct($title, $description){
        $this->title = $title;
        $this->description = $description;
    }
}

// Create a new object, passing in a $title and $description
$task = new Task('Learn OOP','This is a description');

// Try it and see
var_dump($task->title, $task->description);

For more details on what a constructor is, see the manual.


class Person{
 private $fname;
 private $lname;

 public function __construct($fname,$lname){
  $this->fname = $fname;
  $this->lname = $lname;
 }
}
$objPerson1 = new Person('john','smith');

__construct is always called when creating new objects or they are invoked when initialization takes place.it is suitable for any initialization that the object may need before it is used. __construct method is the first method executed in class.

    class Test
    {
      function __construct($value1,$value2)
      {
         echo "Inside Construct";
         echo $this->value1;
         echo $this->value2;
      }
    }

//
  $testObject  =  new Test('abc','123');

I believe that function __construct () {...} is a piece of code that can be reused again and again in substitution for TheActualFunctionName () {...}. If you change the CLASS Name you do not have to change within the code because the generic __construct refers always to the actual class name...whatever it is. You code less...or?


__construct is a method for initializing of new object before it is used.
http://php.net/manual/en/language.oop5.decon.php#object.construct


Note: Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required. If the child does not define a constructor then it may be inherited from the parent class just like a normal class method (if it was not declared as private).


__construct simply initiates a class. Suppose you have the following code;

Class Person { 

 function __construct() {
   echo 'Hello';
  }

}

$person = new Person();

//the result 'Hello' will be shown.

We did not create another function to echo the word 'Hello'. It simply shows that the keyword __construct is quite useful in initiating a class or an object.

참고URL : https://stackoverflow.com/questions/455910/what-is-the-function-construct-used-for

반응형