0
0

More than 3 years have passed since last update.

オブジェクト指向 メンバ関数にメンバ変数を代入する方法

Posted at

はじめに

メンバ関数にそのクラス内で作成したメンバ変数を引数にしようとした時に構文エラーがでたため、どのようにしたらいいのかを考えた。

したこと

TodoValidationクラスでcheckメソッドを作成し、そのメソッドをcontrollerで呼び出そうとしたコードが以下である。

public function check($this->str)
    {
        // 空文字チェック
        if (empty($this->str)) {
            return   $_SESSION['err_msg'] = '入力してください';
        }
    }

このメソッドをcontroller側で呼び出そうと以下のコードを書いた。

$toDoValidation->check($this->product_name);

が、フィールドに値を入力してPOST送信してもセッション変数のエラーメッセージは空になっていた。

原因

メンバ関数の引数にメンバ変数は代入できない決まりがある。
なので、

public function check($str)
    {
        // 空文字チェック
        if (empty($str)) {
            return $_SESSION['err_msg'] = '入力してください';
        } else {
            return true;
        }
    }

というようにメンバ関数の引数に変数を入れることによって正しくバリデーションを行うことができた。

どうしてもメンバ変数を使用したい場合

以下のように記述する。

public function check($str)
    {
        $this->str = $str;
        // 空文字チェック
        if (empty($this->str)) {
            return   $_SESSION['err_msg'] = '入力してください';
        }
    }
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0