Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
0
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

@agrokic

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

最近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
0
Help us understand the problem. What are the problem?