OOP PHP 在一个函数中设置变量值并从另一个函数中获取 [英] OOP PHP set variable value in one function and get from another function

查看:55
本文介绍了OOP PHP 在一个函数中设置变量值并从另一个函数中获取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的课堂上,我试图在 __construct()

In my class, I am trying to set the value of a variable in a function other than __construct()

但我需要在另一个函数中使用该变量值.

But I need that variable value in another function.

这是我尝试过的.但不能正常工作.

Here is what I have tried. But not works Properly.

我希望打印 getty images 但我什么也没得到 :(

I expect to print getty images but I get nothing :(

<?php

class MyClass{
    public $var;

    public function __construct(){
        $this->var;
    }

    public function setval(){
        $this->var = 'getty Images';
    }

    public function printval(){
        echo $this->var;
    }
}

$test = new MyClass();
$test->printval();

推荐答案

你的构造函数什么都不做,你需要调用方法让它做一些事情.

Your constructor does nothing, you need to invoke the method for it to do something.

class MyClass{
    private $var;

    public function __construct() {
        // When the class is called, run the setVal() method
        $this->setval('getty Images');
    }

    public function setval($val) {
        $this->var = $val;
    }

    public function printval() {
        echo $this->var;
    }
}

$test = new MyClass();
$test->printval(); // Prints getty Images

这篇关于OOP PHP 在一个函数中设置变量值并从另一个函数中获取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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