调用方法/函数中的对象变量


Calling object variable in method/ function

如何调用方法中包含对象的变量?任何建议和帮助都将不胜感激。

以下是我进一步解释的例子,

这是我的类脚本shirt.php

<?php 
    class shirt {
        //some function and code here
        public getSize() {
            return $this->size;
        }
    }
?>

这是我调用shirt.php的脚本,该脚本名为shirt.func.php

<?php
    require_once 'shirt.php';
    $shirt = new Shirt();
    function getShirtSize() {
        return $shirt->getSize();
    }
?>

问题是我不能在函数中使用变量$shirt,但如果我在函数外使用它,它会完美工作。我找到了一种解决方法,那就是创建一个返回该对象初始值的方法。

这是我的方式:

<?php
    require_once 'foo.php';
    function init() {
        return $shirt = new Shirt();
    }
    function getShirtSize() {
        return init()->getSize();
    }
?>

还有其他有效的方法吗?感谢您的专业建议。

方法和函数有自己的作用域。它们只知道对象和标量,您可以显式地为它们提供。因此,您必须将对象传递到函数中。

require_once 'shirt.php';
$myCurrentShirt = new Shirt();
function getShirtSize($shirt) {
    return $shirt->getSize();
}

将执行此操作。有关函数使用的更多信息,请参阅手册。

require_once 'shirt.php';
$shirt = new shirt();
function getShirtSize($_shirt) {
    return $_shirt->getSize();
}
getShirtSize($shirt) // pass the $shirt to the function

编辑:

或者(不那么(伟大的全球:

require_once 'shirt.php';
$shirt = new shirt();
function getShirtSize() {
    global $shirt;
    return $shirt->getSize();
}
getShirtSize();