我无法将一个对象从一个函数调用到另一个函数

时间:2014-09-09 05:18:47

标签: php

我有以下代码,但我无法打印对象名称:

   <?php
       class persons {
         public function people(){ //__construct OR persons to class define constructor 
               $this->name="pepe";
         }

         public function print_1(){
                echo $this->name;
                echo '<br>';
         }
    }

    $per1=new persons();
    $per1->print_1();
    ?>

3 个答案:

答案 0 :(得分:1)

您的init函数永远不会执行,因此永远不会设置名称 如果您打算使用构造函数you need to name it __construct

(关于保留的print关键字的其他错误也适用。)

答案 1 :(得分:0)

假设您有致命错误,因为print是保留关键字,您不能使用类method名称,请使用其他名称,请参阅下文

<?php
       class persons {
         var $name = "";

         public function people(){ 
               $this->name="pepe";
         }

         public function print_1(){
                echo $this->name;
                echo '<br>';
         }
    }

    $per1=new persons();
    $per1->people();
    $per1->print_1();
    ?>

由于@deceze在评论__construct()ClassName方法中提及类构造以初始化值

DEMO

答案 2 :(得分:-1)

您需要在对象中定义$name。您还有print()我认为您无法使用。你必须做出类似_print的其他内容。

<?php
    class persons
        {
            public $name;
            public function init(){
                     $this->name = "pepe";
                 }

             public function _print(){
                     echo $this->name;
                     echo '<br>';
                 }
        }

    $per1 = new persons();
    // If you don't define your name in a class you use (ie. you should define it in your $this->_print()), you can define it outside
    // It's not the greatest solution. but it will work.
    $per1->name = 'pepe';
    $per1->_print(); ?>

您还可以在init()内定义_print(),如下所示:

 <?php
        class persons
            {
                public $name;
                public function init(){
                         $this->name = "pepe";
                     }

                 public function _print(){
                          $this->init();
                         echo $this->name;
                         echo '<br>';
                     }
            }

        $per1 = new persons();
        $per1->_print(); ?>