search
HomeBackend DevelopmentPHP TutorialPHP类属性的权限问题 ctrl+v 第一次用第一次被喷 正视过后仅以警醒

让我无法理解的代码,哪位老师或高手能指点指点,万分感谢。
代码如下:

<?php
class person {
    private $n1;
    private $n2;
    private $n3;

    public function __set($pro_name, $pro_val){
        $this->{$pro_name} = $pro_val;
    }

    public function __get($pro_name) {
        if (!isset($this->{$pro_name})) {
            return null;
        } else {
            return $this->{$pro_name};
        }
    }
}


class a {
    public $n;
    public $x;

    public function __construct($in, $ix) {
        $this->n = $in;
        $this->x = $ix;
    }
}

$pef1 = new person();
$pef1->n1 = '小明';
$pef1->n2 = 200;
echo $pef1->n1, '||', $pef1->n2;

echo PHP_EOL;

$c = new a('小小', 2003);
echo $c->n, '||', $c->x;

第一个person类和第二个a类的调用问题,第一个类的成员属性是私有的,老师说过可以用__set__get来统一来管理,这个没问题。可问题是创建对象的时候,我可以不用和创建的对象名一致就能调用。比如说:我创建一个person类,然后再创建一个$p1=new person();对象,然后我调用,正常是这个的$p1->n1="小明";但现在我却不用这样也能调用,$uu->n1="小明";。这是为什么呢?

第二个a类主要是我为了证明是不是所有的类在创建对象后,都可以不用对象名来调用,结果发现不行。这个我可以理解,但第一种我就不能理解了。为什么protectedprivate的成员属性和方法在使用了__set__get这一对函数后在对象调用的时候就可以不用对象名呢?

回复内容:

让我无法理解的代码,哪位老师或高手能指点指点,万分感谢。
代码如下:

<?php
class person {
    private $n1;
    private $n2;
    private $n3;

    public function __set($pro_name, $pro_val){
        $this->{$pro_name} = $pro_val;
    }

    public function __get($pro_name) {
        if (!isset($this->{$pro_name})) {
            return null;
        } else {
            return $this->{$pro_name};
        }
    }
}


class a {
    public $n;
    public $x;

    public function __construct($in, $ix) {
        $this->n = $in;
        $this->x = $ix;
    }
}

$pef1 = new person();
$pef1->n1 = '小明';
$pef1->n2 = 200;
echo $pef1->n1, '||', $pef1->n2;

echo PHP_EOL;

$c = new a('小小', 2003);
echo $c->n, '||', $c->x;

第一个person类和第二个a类的调用问题,第一个类的成员属性是私有的,老师说过可以用__set__get来统一来管理,这个没问题。可问题是创建对象的时候,我可以不用和创建的对象名一致就能调用。比如说:我创建一个person类,然后再创建一个$p1=new person();对象,然后我调用,正常是这个的$p1->n1="小明";但现在我却不用这样也能调用,$uu->n1="小明";。这是为什么呢?

第二个a类主要是我为了证明是不是所有的类在创建对象后,都可以不用对象名来调用,结果发现不行。这个我可以理解,但第一种我就不能理解了。为什么protectedprivate的成员属性和方法在使用了__set__get这一对函数后在对象调用的时候就可以不用对象名呢?

不好意思我把题主问题里的代码修改了,我觉得题主的代码出现了一些思维问题,是因为题主完全对 PHP 面向对象了解太少。现在不得不使出八字箴言—— RTFMSTFW

题主的关键问题在于要理解 PHP 面向对象中 publicprotectedprivate 对于权限的影响,还有 PHP 魔术方法的原理。

给几个链接仅供题主参考:

http://www.php.net/manual/zh/language.oop5.overloading.php

http://www.php.net/manual/zh/language.oop5.magic.php

http://www.php.net/manual/zh/language.oop5.visibility.php

你是不是很奇怪为什么没创建的对象也还能对属性赋值?是不是?
如果真的是的话,我真觉得骚年你图样图森破啊!

你这里的$uu$g都不是person类实例化的对象好么,不信你执行var_dump()把三个都输出出来看看:

<code>var_dump($pef1);
var_dump($uu);
var_dump($g);
</code>

你会发现$pef1n1/n2/n3三个成员变量都有,而$uu$g中只有你赋值的属性。所以可以说明根本不是你所谓的person类实例化的对象好么!只是你恰好的用了n1属性而已。这段代码里头的$uu->n1$g->n1的作用基本等同于一个变量了,没有太大的讨论意义。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools