实例化类并使用方法填充对象

问题描述 投票:1回答:1

嘿,我正在用PHP测试一些OPP原理

我创建了一个类,该类的方法带有两个参数。

当我实例化一个类并使用参数的数据调用方法时,我什么也没得到。

<?php

class example
{
    public $request;

    public function test($uprn, $sourceChannel)
    {
        $this->request = new stdClass();
        $this->request->uprn = $uprn;
        $this->request->sourceChannel = $sourceChannel;

    }

}

$test = new example();
$test->test('1', '2');

var_dump($test);die;

我在浏览器中得到的都是一个空对象,如下所示:

object(example)#1 (0) { }

但是我希望这样:

object(example)#1 (2) { ["uprn"]=> string(1) "1" ["sourceChannel"]=> string(1) "2" }

知道我要去哪里错了吗??

php
1个回答
1
投票

stdClass是PHP的通用空类,类似于Java中的Object或Python中的对象(编辑:但实际上并未用作通用基类;感谢@Ciaran指出这一点)。它对于匿名对象,动态属性很有用。

您可以像这样获得所需的输出。

$request = new stdClass();
$request->uprn = $var1;
$request->sourceChannel = $var2;
var_dump($request);die; 

请通过此链接了解通用空类(stdClass)。http://krisjordan.com/dynamic-properties-in-php-with-stdclass

在PHP OOPS中,您可以获得以下给出的输出

class example
{
    var $uprn,$sourceChannel; 

    public function test($uprn, $sourceChannel)
    {        
        $this->uprn = $uprn;
        $this->sourceChannel = $sourceChannel;
    }}

$test = new example();
$test->test('1', '2');
var_dump($test);die;

为了更好地理解http://php.net/manual/en/language.oop5.php

© www.soinside.com 2019 - 2024. All rights reserved.