不在对象上下文中使用$ this php [英] Using $this when not in object context php

查看:68
本文介绍了不在对象上下文中使用$ this php的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始用php学习OOPS.我写了一个简单的程序来实现继承.当不在对象上下文中时,我得到致命错误$ this.谁能解释这个错误,这是什么意思? 这是我的代码:

I just started learning OOPS in php. I wrote a simple program for implementing inheritance. I am getting a fatal error of $this when not in object context. Can anyone explain me this error, what does it mean? here is my code:

<?php

    class human{

        public $gender;

        public function _construct($gender)
        {
            $this->gender=$gender;

            echo $this->get_gender();
        }

        public function get_gender()
        {
            return $this->gender;
        }


    }

    class person extends human{

        public $name;
        public $surname;

        public static function set_name($name)
        {
            $this->name=$name;
        }
        public static function set_surname($surname)
        {
            $this->surname=$surname;
        }

        public static function get_name()
        {
            return $this->name;
        }
        public static function get_surname()
        {
            return $this->surname;
        }
    }

    $john = new person('male');
    $john->set_name('John');
    $john->set_surname('Williams');
    echo $john->get_name().' '.$john->get_surname().'is a '.$john->get_gender();
    ?>

推荐答案

这里有两个问题:

  1. 您已将方法定义为static.您不应该那样做,因为您想要使用对象的非静态属性,它们依赖于在对象上被调用.

  1. You have defined your methods as static. You should not do that as they are not, they depend on being called on an object as you want to use the objects non-static properties.

构造函数中有一个错字.构造函数的正确名称是__construct,请注意开头的两个_.

You have a typo in your constructor function. The correct name for the constructor is __construct, notice the two _ at the beginning.

这篇关于不在对象上下文中使用$ this php的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆