Private Var Is Accessible from Outside the Class

Why private variable declared outside the class can be access Class on the same file?

private is intended for use inside a type declaration. Otherwise it has no meaning. When private is used in a place where it has no meaning, it is reinterpreted as fileprivate. That is what happens here. This code is in the same file so the fileprivate variable is visible.

Why is it possible to access private variables from outside class by reference?

Well, you are explicitly returning a reference to a value. You're locking the front door, but are then opening a side entrance. You are very deliberately taking aim and shooting your own foot here. If $property was an object, and you'd return this object with or without & reference, any modifications to this object would be reflected on $property as well. That's how a reference works, it always modifies the one and only existing value that the reference points to.

Visibility modifiers aren't magic iron clad "protections". There are any number of ways how you can circumvent a private visibility to access and modify the property. They're mostly there as a flag to yourself and other developers that this property should not be accessed directly, it's for internal use and not a publicly sanctioned API. And PHP will slap you on the wrist should you forget that. Nothing more, nothing less.

Also, nothing is really being violated here. Outside code is at no point accessing or modifying $obj->property. That's the only thing private is supposed to prohibit. You're essentially exposing a public API on your object which modifies a private property. Usually this is done with getter and setter functions, but a by-reference API obviously works as well.

Private var is accessible from outside the class

Access modifiers in Swift are implemented differently than other languages. There are three levels:

private: accessible only within that particular file

internal: accessible only within the module (project)

public: accessible from anywhere

Unless marked otherwise, everything you write is internal by default.

The Swift blog had a post about access control when the features were introduced in beta 4, and Apple's documentation has a chapter as well.

Why am I able to access private class variables from outside the class, and how can I prevent it?

As explained in the documentation, A class's private section can be accessed from anywhere within the unit where that class is defined. In order to avoid this, and eliminate access to these private class members from elsewhere in the same unit, use strict private instead.

Of course, if your application's design calls for it, you could also move this class over to another unit, which in turn would produce the effect you're looking for as well.



Related Topics



Leave a reply



Submit