Help us understand the problem. What is going on with this article?

PHP演算子->,=>,::の異なる点

More than 1 year has passed since last update.

最近PHPを学んている、書くよく紛らわしい演算子についてのまとめです。

『->』と『$this』

『->』は左側のメンバーを右側の関数や変数などで使うことです。$this(疑似変数)はオブジェクト中に属性(変数)とメソード(関数)を指定と定義するものです。

->.php
<?
class getprice{
    public $fruit;
    public $price;
    public $number;
    public function name(){
        return $this->fruit;//$fruitの内容
    }
    public function total(){
      return  $this -> number*$this -> price;
    }

}

$astore=new getprice;//オブジェクトを作る
$astore -> fruit= 'apple';
$astore -> number= 3;
$astore -> price= 100;


echo $astore->name();
echo $astore ->total();
?>

『=>』

配列中の『キー=>値』の示す符号です。

=>.php
<?
$students = array('sam','larry','tom');
foreach ($students as $key => $student) {
    echo "{$key} => {$student}";
    print_r($arr);
}
?>

『::』

static宣言のメソードを呼び出す方法です。$thisは静的コールをできません。

error.php
<?
class getprice{
    public $fruit;
    public $price;
    public $number;
    public function name(){
        return $this->fruit;
    }
    public static function total(){
      return  $this -> number*$this -> price;
    }

}

$astore=new getprice;
$astore -> fruit= 'apple';
$astore -> number= 3;
$astore -> price= 100;


echo $astore->name();
echo $astore ->total();
?>
エラー:Fatal error: Uncaught Error: Using $this when not in object context

『::』を直して、静的コールをします。

right.php
<?
class getprice{
    public $fruit;
    public $price;
    public $number;
    public function name(){
        return $this->fruit;
    }
    public  function total(){
      return  $this -> number*$this -> price;
    }
    public static function get($a,$b){
        return $a*$b;
      }

}

$astore=new getprice;
$astore -> fruit= 'apple';
$astore -> number= 3;
$astore -> price= 100;


echo $astore->name();
echo $astore->total();
echo $astore::get(10,3);
?>
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした