php 문법 질문있습니다..
본문
<?php
class Variable
{
public $name = "PHPStudy";
public $year = 2018;
public function phpStudy($year)
{
echo "변수 name은 {$this->name} 입니다. <br/>";
echo "변수 year은 {$this->year} 입니다. <br/>";
echo $this->name . $this->year . "<br/>";
}
}
$variable = new Variable();
$variable->phpStudy();
?>
php 이런 에러가 나타납니다 뭐가 문제일까요 ㅠㅠ
Missing argument 1 for Variable::phpStudy(), called in /home/hosting_users/root/variable.php on line 17 and defined in /home/hosting_users/root/variable.phpon line 8
!-->답변 3
생성자가 없어 phpStudy()함수에서 $year의 값을 참조하지 못하는것 같습니다.
생성자를 호출하려면 아래 소스처럼 하시면 될 것 같네요
또는 질문내용과 같은 형식으로 하시려면 function phpStudy() { ... } 이렇게 인자만 빼주시면 될것 같습니다.
<?php
class Variable
{
public $name;
public $year;
function __construct(){
$this->year = 2018;
$this->name = "PHPStudy";
}
function __destruct(){
}
public function phpStudy()
{
echo "변수 name은 {$this->name} 입니다. <br/>";
echo "변수 year은 {$this->year} 입니다. <br/>";
echo $this->name . $this->year . "<br/>";
}
}
$variable = new Variable();
$variable->phpStudy();
?>
6행에 보면,
클래스 안의 함수 phpStudy 에 $year 라는 argument 가 있네요.
phpStudy 메서드에 기본 파라미터 값을 입력해 주지 않아서 발생하는 오류입니다. $variable->phpStudy(2018); 처럼 사용하시거나 아니면 아래처럼 사용하시는게 좋습니다.
<?php
class Variable
{
public $name = "PHPStudy";
public $year = 2018;
public function phpStudy($year=null)
{
if($year===null){
$year=$this->year;
}
echo "변수 name은 {$this->name} 입니다. <br/>";
echo "변수 year은 {$this->year} 입니다. <br/>";
echo $this->name . $this->year . "<br/>";
}
}
$variable = new Variable();
$variable->phpStudy();
?>
답변을 작성하시기 전에 로그인 해주세요.