Natty’s blog

Stay hungry. Stay foolish. — Steve Jobs

[PHP] สิ่งหนึ่งที่ทำให้เกิด Call to a member function on a non-object

Posted by natty on November 19, 2008

วันนี้ แก้ error โง่ๆ ไปพักหนึ่ง ด้วยความมึน ตอน run PHP แล้วเกิด คือ พยายามจะ new object แต่ว่าไม่สามารถจะ new ได้ และหลังจาก new ก็ไปใช้ method ของมัน ทำให้มันบอกว่า ใช้ function จากตัวที่ไม่เป็น object ไม่ได้ อย่างเช่น


$test = new AR(new Ds());

$test->getDS();

มันจะเรียก getDS(); ไม่ได้ เพราะ $test ยังเป็น null

มาเล่น PhotoHunt กัน ให้ดูว่า class ของ Ds ทำอะไร


var $dsStrategy;
public function _construct (iDSStrategy $dsStrategy){
$this->dsStrategy = $dsStrategy;
}
public  function getValForCreditFromCore(){
$this->dsStrategy->getValForCreditFromCore();
} 

นี่แหละ ทำให้เกิด Call to a member function on a non-object งงเลยใช่ไหมว่าทำไม

เหตุผลสำหรับ code นี้ เพราะที่ใส่ underscore หน้า constructor ไปอันเดียว – -”

ที่ถูกต้องเป็น

public function __construct (iDSStrategy $dsStrategy)

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>