dongsun2789 2013-10-04 12:44 采纳率: 100%
浏览 55
已采纳

PHP类:定义默认返回对象

I have a PHP Class with a Constructor and some Methods. Every Method need to have the same return stdClass Object. Only a few properties in each functoin of the stdClass Object should be diffrent from the default one(like the property value or status). How would you do that? I mean, i can define in every function an stdClass Object with all properties, but as I said, I only need to change a few properties in each function for the return.

Examplecode which doesn't work:

<?
    class Person{
        public $sName;
        public $oReturn = new stdClass();
        $oReturn->status = 200;
        $oReturn->value = "Personname";

        function __construct($sName) {
            $this->sName = $sName;
        }

        public function something($oData){
            //Declaration
            $this->oReturn->value = $oData->newName;
            //Main

            //Return
            return $this->oReturn;
        }
    }
?>
  • 写回答

4条回答 默认 最新

  • dpi9530 2013-10-04 12:51
    关注

    You can't declare properties like this:-

    public $oReturn = new stdClass();
    

    That is illegal in PHP. Do it like this:-

    class Person{
        public $sName;
        public $oReturn;
    
        function __construct($sName) {
            $this->sName = $sName;
            $this->oReturn = new stdClass;
            $this->oReturn->status = 200;
            $this->oReturn->value = "Personname";
        }
    
        public function something($oData){
            //Declaration
            $this->oReturn->value = $oData->newName;
            //Main
    
            //Return
            return $this->oReturn;
        }
    }
    

    Now you can set whatever properties you want in $this->oReturn which, I think, is what you want to achieve.

    See it working

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错