【问题标题】:Set a non-string variable in a function in a class to get in other PHP files class在类中的函数中设置非字符串变量以获取其他 PHP 文件类
【发布时间】:2017-01-13 12:19:18
【问题描述】:

首先:

在 main.php 上,我可以使用 $this->tester1 在函数之间共享变量,因此我需要 public $tester1;在我的文件顶部 - 没有它似乎可以正常工作?

其次:

我正在尝试获取 other.phpma​​in.php 中设置的变量,如果我从函数中删除 $this->tester1 = 'test'; 并设置 public $tester1 to = 'test'; 然后 @任何一个文件上的 987654324@ 都可以正常输出。

但是,我需要的变量不是“测试”,而是 = get_option( 'my_option' );,它需要在 init 操作上的 __construct 之后调用,因此需要在函数 mymainfunction 内。

如果我尝试在该函数中设置变量并尝试通过 other.php 访问它,它会显示 unexpected PUBLIC,如果我从变量中删除 public 则输出是 未定义的属性: MyMainClass::$tester1

get_option 的输出是一行文本。

我想我几乎可以做到这一点,但缺少一些简单的东西——希望如此! :)

这是我的文件:

ma​​in.php

class MyMainClass {

    public $tester1;

    public function __construct() {
        add_action( 'init', array( &$this, 'mymainfunction' ) );
    }

    public function mymainfunction() {
        $this->tester1 = 'test';
        echo $this->tester1;
    }

}

other.php

class MyOtherClass {

    public function __construct() {
        add_action( 'init', array(&$this, 'myotherfunction' ) );
    }

    public function myotherfunction() {
        require_once 'main.php';
        $getvariables = new MyMainClass();
        echo 'tester1 is:' . $getvariables->tester1;
    }


}

【问题讨论】:

    标签: php class oop


    【解决方案1】:

    首先:

    如果我没记错的话,没有任何显式可见性关键字的声明被定义为公共。

    其次:

    您在另一个方法的中间包含一个类。对我来说似乎很奇怪..“require_once”只是插入一个文件的内容,该指令被调用。所以我的猜测是它与 PHP 语法混淆了。为了帮助您,您是否尝试将“other.php”替换为:

    require_once 'main.php';
    class MyOtherClass {
    
        public function __construct() {
            add_action( 'init', array(&$this, 'myotherfunction' ) );
        }
    
        public function myotherfunction() {
            $getvariables = new MyMainClass();
            echo 'tester1 is:' . $getvariables->tester1;
        }
    }
    

    但老实说,我不知道你想做什么,但这样的事情会更简单,对吧?

    ma​​in.php

    class MyMainClass {
        public $tester1;
    
        public function __construct() {
            $this->tester1 = 'test1';
        }
    }
    

    other.php

    require_once 'main.php';
    class MyOtherClass {
        public function __construct() {
            $main = new MyMainClass();
            echo 'tester1 is:' . $main->tester1;
        }
    }
    

    【讨论】:

    • 这适用于字符串,但我想将 get_option 存储在我无法在 __construct 中执行的问题中,仅存储在它调用 init 的函数上。
    猜你喜欢
    • 2014-09-22
    • 2013-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多