初級 › Call to a member function on null の原因と直し方 › パターン4
Call to a member function on null の原因と直し方
nullが入った変数に対してメソッドを呼び出そうとしたときに出るエラーです。
1 <?php 2 class Cart { 3 public function total() { return 0; } 4 } 5 function getCart() { return __________; } ^ 6 $cart = getCart(); 7 echo $cart->total();
Fatal error: Uncaught Error: Call to a member function total() on null in main.php:7
空欄を埋めて実行を通す
getCart()がnullを返しているため、$cartはオブジェクトになっていません。
次の問題