如何在PHP中使用内部类? [英] How do I Use Inner Classes in PHP?

查看:4643
本文介绍了如何在PHP中使用内部类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来自Java背景,我想在php中使用一个内部类。每次我把内部类,但我得到一个语法错误。这是可能与PHP吗?此外,如何引用外部类?我可以访问其所有数据成员吗?

I'm from a Java background, and I want to use an inner class in php. Every time I put the inner class though, I get a syntax error. Is this possible with PHP? Also, how do I reference the outer class? Do I get access to ALL its data members?

<?php

class OuterClass {
    var $x = 15;
    function __construct() {

    }

    class InnerClass {                  // error when InnerClass is static
        function __construct() {        // error when InnerClass is static
            echo $x;
        }
    }
}

?>

这用于特定纸牌游戏的MoveClass我认为把这些类放在一起是好的设计,因为他们没有意义分开。此外,MoveClass需要知道Game类的一些数据成员。为什么不让它成为一个函数?这太大了。

This is used for a MoveClass (as in make a move) of a specific card game. I think it'd be good design to put these classes together because they don't make sense apart. Also, the MoveClass needs to know about some data members of the Game class. Why not make it a function? It's simply too big.

编辑:

嵌套类怎么样?从我的理解,那些必须是静态的? O_o

What about nested classes? From what I understand, those have to be static? O_o

推荐答案

PHP不允许内部类。如果你想访问父类的所有数据成员,我建议你使用继承。

PHP does not allow for inner classes. Should you wish to access all of the data members from the parent class, I would suggest you employ Inheritance.

一种可能的替代方法:

class OuterClass {
    var $x = 15;
    function __construct() {

    }
}
class ChildClass extends OuterClass {
    function __construct() {
        parent::__construct();
    }
}

您可以通过引用到类本身;在PHP中,您可以使用 parent 关键字。因此,为了在类的上下文中引用一个方法,而不是一个对象,我们使用 :: 而不是 - >

You can envoke a method form the parent class by referring to the class itself; In PHP you can do this with the parent keyword. So, to refer to a method in the context of a class rather than an object we use :: as opposed to ->.

这篇关于如何在PHP中使用内部类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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