php类声明与实例化的区别?
習慣沉默
習慣沉默 2017-05-16 13:10:23
0
2
442

我是一个菜鸟新手,我发现很多工具类,直接声明就能用了,例如laravel里的

Request $request;
$request->get();

这让我很不解,声明一个类变量难道就实例化了码?
百度了一下,关于这个问题php语言居然没有一个人问,只有java,java是这样的:
Class1 item1;声明一个对象
生成一个引用类型,占4字节内存,不管是什么类型(object o或From f)的引用都是占用4字节内存
Class1 item1 = new Class1();
创建一个类实例,开辟一块内存(这块内存跟类本身的大小有关),并且让引用item1指向这块内存的起始位置;

如果是这样,$request只是一个Request的引用,而Request还没实例化,在内存中是不存在的,那为什么$request能直接用里面的方法呢?看了一下源代码,虽然这个类里面的属性和方法有static静态的,在实例化之前就已经存在内存中了,但也有很多非静态的属性和方法啊,get()就是一个非静态方法!

直接调用不会引起指针异常吗?
新手求问!

習慣沉默
習慣沉默

reply all(2)
Ty80

PHP doesn’t have this kind of syntax
What you see should be something like this
Route::get('/', function (IlluminateHttpRequest $request) {

return view('welcome', ['a'=>$request->get('a',1)]);

});
This is dependency injection
http://www.golaravel.com/lara...

过去多啦不再A梦

The following is wrong: After carefully looking at the source code, is the answer like this?
at

Request $request;
$request->get();

Before these two pieces of code, I used use IlluminateHttpRequest;

use just uses the namespace, but if you want to call the class, you must load the class file (require), or load it automatically. , lavavel uses automatic loading, so in our opinion, using IlluminateHttpRequest is equivalent to being able to use the Request class directly. In fact, it is not. Laravel actually does a lot of work when using the Request class!
Laravel’s automatic loading function is as follows:

 public static function getLoader()
    {
        if (null !== self::$loader) {
            return self::$loader;
        }

        spl_autoload_register(array('ComposerAutoloaderInit67db7509c61e60a4f92e012c704d3566', 'loadClassLoader'), true, true);
        self::$loader = $loader = new \Composer\Autoload\ClassLoader();
        spl_autoload_unregister(array('ComposerAutoloaderInit67db7509c61e60a4f92e012c704d3566', 'loadClassLoader'));

        $map = require __DIR__ . '/autoload_namespaces.php';
        foreach ($map as $namespace => $path) {
            $loader->set($namespace, $path);
        }

        $map = require __DIR__ . '/autoload_psr4.php';
        foreach ($map as $namespace => $path) {
            $loader->setPsr4($namespace, $path);
        }

        $classMap = require __DIR__ . '/autoload_classmap.php';
        if ($classMap) {
            $loader->addClassMap($classMap);
        }

        $loader->register(true);

        $includeFiles = require __DIR__ . '/autoload_files.php';
        foreach ($includeFiles as $fileIdentifier => $file) {
            composerRequire67db7509c61e60a4f92e012c704d3566($fileIdentifier, $file);
        }

        return $loader;
    }
}

It can be seen that if you use an uninstantiated class, it will be automatically loaded and instantiated.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!